I'm working on a simple graphical network application, using asyncio and tkinter. I'm running into the problem of combining the asyncio event loop with Tk's mainloop. If possible, I'd like to do it without threads, because both these libraries (but especially tkinter) aren't very thread safe. Currently, I'm using Tk.update in an asyncio coroutine, which runs only a single iteration of the tk event loop:
@asyncio.coroutine
def run_tk(tk, interval=0.1):
try:
while True:
tk.update()
yield from asyncio.sleep(interval)
except TclError as e:
if "application has been destroyed" not in e.args[0]:
raise
However, in the interest of exploring all options, I was wondering if it was possible to do the reverse- if it was possible to invoke only a single iteration of an asyncio event loop inside a tk callback.
update
in a loop, but also creates a traditional event loop to do network i/o and runs it in a thread. It's the worst of both worlds; the only advantage is that direct callbacks (loop.call_later
) are invoked directly in the Tk event loop.run_once
in the tkinter main loop to "run" asyncio.loop._run_once()
. However if you stick thinter to its own thread while running asyncio loop on another there is no problem with that. Most of asyncio is not thread safe either. You can schedule coroutines and callbacks from tkinter thread withloop.run_coroutine_threadsafe()
andloop.call_soon_threadsafe()
respectively.