diff --git a/tkasyncio/tkasyncio.py b/tkasyncio/tkasyncio.py index 7c50624..eeea0c1 100644 --- a/tkasyncio/tkasyncio.py +++ b/tkasyncio/tkasyncio.py @@ -12,6 +12,7 @@ def __init__(self): super().__init__() self.running = True self.runners = [self.tk_loop()] + self.button_presses = [] async def tk_loop(self): "asyncio 'compatible' tk event loop?" @@ -19,12 +20,18 @@ async def tk_loop(self): while self.running: self.update() await asyncio.sleep(0.05) # obviously, sleep time could be parameterized + if len(self.button_presses) > 0: + await self.button_presses.pop(0) def stop(self): self.running = False async def run(self): await asyncio.gather(*self.runners) + + def add_button_coro(self, coro): + task = asyncio.create_task(coro) + self.button_presses.append(task) class App(AsyncTk): @@ -40,6 +47,8 @@ def create_interface(self): b1.pack() b2 = Button(master=self, text='Quit', command=self.stop) b2.pack() + b3 = Button(master=self, text='Foo', command=lambda: self.add_button_coro(self.foo())) + b3.pack() async def counter(self): "sample async worker... (with apologies to Lawrence Welk)" @@ -48,6 +57,11 @@ async def counter(self): print("and a", i) await asyncio.sleep(1) i += 1 + + async def foo(self): + print(f"IO task foo has started") + await asyncio.sleep(1) + print(f"IO task foo has finished") async def main(): app = App()