5

I want to call an async function from a Tkinter button command, or rather want to let the function run asynchronously, so that the tkinter window is responsive.
I've tried command = open_async in the Button, where open_async was declared like so async def open_async():, but it gave me an error "RuntimeWarning: coroutine 'open_async' was never awaited self.tk.mainloop(n)".
If I just used def async():, the code would still run synchronously, thus the UI will be unresponsive. (async() contains some other asynchronous operation inside too, using asyncio and stuff).

Anyone knows how to resolve this? I don't want to create threads too. Thanks

marcus
  • 51
  • 1
  • 5
  • 2
    async functions need an event loop to be executed which in turn needs a thread. You can either mix it with the mainloop of tkinter or run it in a separate thread. Some helpful approaches are at https://stackoverflow.com/questions/47895765/use-asyncio-and-tkinter-or-another-gui-lib-together-without-freezing-the-gui – Michael Butscher Aug 31 '21 at 05:13
  • Why do you want to run the function asynchronously? If you want to implement some kind of loop, [this](https://stackoverflow.com/a/459131/11106801) is the proper way of doing it. If that still doesn't help, you can use threads. – TheLizzard Aug 31 '21 at 09:17

1 Answers1

0

Answering very Late but Use command=lambda : asyncio.run(open_async())

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 09 '23 at 17:02