Connecting Asyncio and Tkinter event loops?

I recently resurrected a long dormant tkinter program. I was mildly
surprised it still worked with no (or minimal) changes. It contained a
commented out chunk of code which read “uncomment for Python 1.4”. :slight_smile:
I’m sure at some point I “ported” it to Python 3, but I don’t recall
if or when that might have happened.

I’ve never used asyncio, but I got to wondering about better tracking
of keyboard and mouse than my little program implements (it’s a
computer activity monitor to force you to rest when needed). I thought
about using pynput, which seems geared toward asyncio. That got me
wondering if providing an async event handler function for tkinter
makes sense. Given that both are in the stdlib, it seems like it might
serve as a template for how it might work for other GUI libraries.

A quick check didn’t reveal anything, but did suggest questions about
linking the tkinter and asyncio event loops do come up from

Hi Skip! When asyncio was first introduced we did give some consideration to integrating it with UI event loops, but other than thinking “it should be possible” I am not aware of anyone actually creating such an integration. :slight_smile:

Thanks, Guido. Would this be the right place to hammer out the details? I can’t see this requiring a PEP unless there are more than two opinions about were such a function belongs. I’ll see if I can create a hello world to start with.

I would love it if you managed to get this working! Agreed that no PEP would be needed. Maybe the new APIs could be in a new submodule of the tkinter package?

We have some (somewhat hacky) asyncio/tk integration in ipykernel: ipykernel/ at fc51ba4cccbc3b56323f9fc75f0ba631916812d9 · ipython/ipykernel · GitHub

I came up with the simplest thing I could get to work (warning: I have never used asyncio before), then extracted just an AsyncTk class. I’m sure it’s missing things a full-fledged asyncio-friendly Tk event loop would need.

You might be interested the Trio “guest mode” approach to the problem of interoperability of an async event loop and a GUI event loop.

I have no experience with it personally, just know that it exists. For what I understand it seems to work. And as asyncio will gain task groups in python 3.11 you may be able to reproduce that approach if you think it is worth it.

1 Like

FWIW, I used the Qt integration projects quamash and then asyncqt for some light GUI work in the past and they felt pretty seamless. They’re unmaintained now, the current successor seems to be qasync.
So yes, it is possible. Thank y’all for thinking about it :‍)