Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added button that can run coroutines #1

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions tkasyncio/tkasyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,26 @@ 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?"
# Is there a better way to trigger loop exit than using a state vrbl?
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):
Expand All @@ -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)"
Expand All @@ -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()
Expand Down