asyncio+tkinter

Skip Montanaro skip.montanaro at gmail.com
Thu Mar 31 20:19:53 EDT 2022


>
> > Given that both asyncio & tkinter are modules in the standard lib and
> both
> > have event loops, I would have expected to find some "best practice"
> > solution to mixing the two.
>
> Agreed. For GTK, you can use a dedicated loop policy like this:
>
> import asyncio_glib
> asyncio.set_event_loop_policy(asyncio_glib.GLibEventLoopPolicy())
>
> It should be possible to make it this easy for asyncio + tkinter.
>

I haven't used GTK in ages and ages, but I do still have a tkinter program
that I drag out every now and then when my wrists start acting up. After
opining about this on the PyIdeas discuss forum, I spent a few minutes and
came up with a simple AsyncTk subclass of tkinter.Tk. Here's its hello
world:

https://gist.github.com/smontanaro/5e12c557602a76c609e46ca59387ad1c

I modified my activity watcher to use it:

https://github.com/smontanaro/python-bits/blob/master/src/watch.py

A few warnings:

   1. copy/paste reuse of that AsyncTk class
   2. the code is a mess (it's probably 20-25 years old, I make no
   apologies for the mess)
   3. as of about an hour ago it now uses pynput to watch for mouse/kbd
   watching

So, Tk+asyncio turns out to be fairly easy to do, at least for simple stuff.

Skip


More information about the Python-list mailing list