OK, now one main block only , but loop.run_forever() ? idk...
Wu Xi
news at luegenpresse.edu
Sun Dec 31 21:35:00 EST 2017
from tkinter import * # I cant see anything wrong with the async_loop business here. It works like a charm.
from tkinter import messagebox # is there a serious concern doing things his way ?
import asyncio , threading , random # goal is multi tasking with the GUI not freezing before loop completed
# which is being achieved here ! works in py 3.7 of 2018
def _asyncio_thread(async_loop):
async_loop.run_until_complete(do_urls())
def do_work(async_loop):
""" Button-Event-Handler starting stuff """
threading.Thread(target=_asyncio_thread, args=(async_loop,)).start()
async def one_url(url):
""" One task. """
global root
sec = random.randint(1, 8)
root.update() # more often
await asyncio.sleep(sec )
return 'url: {} --- sec: {}'.format(url, sec)
async def do_urls():
""" Creating and starting 10 tasks. """
tasks = [one_url(url) for url in range(10)]
completed, pending = await asyncio.wait(tasks)
results = [task.result() for task in completed]
print('\n'.join(results))
def do_notfreeze(): messagebox.showinfo(message='see, Tkinter is still responsive')
if __name__ == '__main__':
global root
async_loop = asyncio.get_event_loop() # all in this loop
root = Tk()
Button(master=root, text='do work', command= lambda:do_work( async_loop )).pack()
Button(master=root, text='Frozen?', command= do_notfreeze ).pack()
root.update()
#async_loop.run_forever() # <---- uncomment, then it won"t work anymore
root.mainloop() # how to replace ?
# To do everything in the main thread,
# one can replace 'root.mainloop' with loop.run_forever (in the main thread)
# and repeated root.update calls.
More information about the Python-list
mailing list