tkinter MP working like a charm

Terry Reedy tjreedy at udel.edu
Mon Jan 1 00:50:37 EST 2018


On 12/31/2017 8:52 PM, Terry Reedy wrote:

> 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.

Wu Xi's example, rewritten more or less as suggested:

from tkinter import *
from tkinter import messagebox
import asyncio
import random

async def one_url(url):
     """ One task. """
     sec = random.randint(1, 8)
     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_nofreeze():
     messagebox.showinfo(message='see, Tkinter is still responsive')

def widgets(master):
     Button(master, text='Frozen?', command=do_nofreeze).pack()

# A production version of this should make it possible to cancel.
# However, when loop stops, updates will stop.
def tk_update(interval):
     root.update()
     loop.call_later(interval, tk_update)

if __name__ == '__main__':
     root = Tk()
     widgets(root)
     loop = asyncio.get_event_loop()
     tk_update(.01)
     loop.run_until_complete(do_urls())



-- 
Terry Jan Reedy




More information about the Python-list mailing list