"""Proof of concept: integrate tkinter, asyncio and async iterator. Terry Jan Reedy, 2016 July 25 """ import asyncio import tkinter as tk import datetime class atimer(): """Yield ticks (None) at intervals. If tick0, yield initial tick. If n, stop after n + tick0 ticks. """ def __init__(self, interval, n=0, tick0=False): self.interval = interval self.tick0 = tick0 self.end_time = loop.time() + (n + .9) * interval if n else 0 async def __aiter__(self): return self async def __anext__(self): if self.tick0: self.tick0 = False return await asyncio.sleep(self.interval) if not self.end_time or (loop.time() <= self.end_time): return else: raise StopAsyncIteration class App(tk.Tk): def __init__(self, loop, interval=.01): super().__init__() self.loop = loop self.interval = interval self.protocol("WM_DELETE_WINDOW", self.close) self.create_widgets() self.tasks = [] self.tasks.append(loop.create_task(self.clock(1))) self.tasks.append(loop.create_task( self.bg_flip(self.hello, 'light red', .217))) self.updater() def create_widgets(self): self.hello = tk.Label(self, text='Hello World', bg='white') self.dtime = tk.Label(self) self.hello.pack() self.dtime.pack() async def clock(self, interval): async for tick in atimer(interval, tick0=True): self.dtime['text'] = datetime.datetime.now() async def bg_flip(self, widget, color, interval): async for tick in atimer(interval): bg = widget['bg'] widget['bg'] = color if bg == 'white' else 'white' def updater(self): self.update() self.loop.call_later(self.interval, self.updater) def close(self): for task in self.tasks: task.cancel() self.loop.stop() self.destroy() loop = asyncio.get_event_loop() app = App(loop) loop.run_forever() loop.close()