Calling async function from button command Tkinter
Asked Answered
A

1

6

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

Antetype answered 31/8, 2021 at 4:38 Comment(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 #47896265Gantline
Why do you want to run the function asynchronously? If you want to implement some kind of loop, this is the proper way of doing it. If that still doesn't help, you can use threads.Helle
H
0

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

Hebdomadary answered 6/7, 2023 at 18:34 Comment(3)
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.Superordinate
This answer does not work: gives error asyncio.run() cannot be called from a running event loopGelman
This is an answer that shows how this can bu done as minimal reproduceable exampleGelman

© 2022 - 2024 — McMap. All rights reserved.