Certainly! Integrating asyncio with Tkinter can be a bit tricky since Tkinter isn't inherently asynchronous. However, by using a separate thread to run the asyncio event loop and communicating with the Tkinter main thread safely, we can achieve the desired functionality.
Below is a comprehensive implementation of the ThreadWorker class that fulfills your requirements:
import asyncio
import concurrent.futures
import threading
import queue
import tkinter as tk
from functools import partial
from typing import Any, Callable, Optional, Union
class ThreadWorker:
def __init__(self, root: tk.Tk):
"""
Initializes the ThreadWorker.
Args:
root (tk.Tk): The main Tkinter window. Used to schedule callbacks in the main thread.
"""
self.root = root
self.task_queue = asyncio.Queue()
self.callback_queue = queue.Queue()
self.loop = asyncio.new_event_loop()
self.thread = threading.Thread(target=self.start_loop, daemon=True)
self.thread.start()
self._stop_event = threading.Event()
self.root.after(100, self.process_callbacks)
def start_loop(self):
"""Starts the asyncio event loop in a separate thread."""
asyncio.set_event_loop(self.loop)
self.loop.create_task(self.worker())
self.loop.run_forever()
async def worker(self):
"""Continuously processes tasks from the task_queue."""
while not self._stop_event.is_set():
func, callback, future = await self.task_queue.get()
try:
if asyncio.iscoroutinefunction(func):
result = await func()
else:
# Run synchronous functions in a ThreadPoolExecutor
result = await self.loop.run_in_executor(None, func)
if callback:
self.callback_queue.put(partial(callback, result))
if future:
future.set_result(result)
except Exception as e:
if callback:
self.callback_queue.put(partial(callback, e))
if future:
future.set_exception(e)
finally:
self.task_queue.task_done()
def enqueue_task(
self,
func: Callable[..., Any],
callback: Optional[Callable[[Any], None]] = None,
) -> Optional[asyncio.Future]:
"""
Enqueue a task to be run in the background.
Args:
func (Callable): The function or coroutine to execute.
callback (Optional[Callable]): A callback to be called with the result.
Returns:
Optional[asyncio.Future]: A future that can be awaited if func is a coroutine.
"""
if asyncio.iscoroutinefunction(func):
future = self.loop.create_future()
self.task_queue.put_nowait((func, callback, future))
return future
else:
self.task_queue.put_nowait((func, callback, None))
return None
async def enqueue_task_async(self, func: Callable[..., Any]) -> Any:
"""
Enqueue a task and await its result.
Args:
func (Callable): The function or coroutine to execute.
Returns:
Any: The result of the function.
"""
future = self.loop.create_future()
self.task_queue.put_nowait((func, None, future))
return await future
def process_callbacks(self):
"""
Process callbacks from the callback_queue and schedule them in the Tkinter main thread.
"""
while not self.callback_queue.empty():
callback = self.callback_queue.get()
try:
callback()
except Exception as e:
print(f"Error in callback: {e}")
self.callback_queue.task_done()
self.root.after(100, self.process_callbacks)
def stop(self):
"""Stops the asyncio loop and the worker thread."""
self._stop_event.set()
self.loop.call_soon_threadsafe(self.loop.stop)
self.thread.join()
# Example Usage with Tkinter
def main():
import time
root = tk.Tk()
root.title("ThreadWorker Example")
worker = ThreadWorker(root)
def sync_task():
print("Starting synchronous task")
time.sleep(2) # Simulate a long-running task
print("Synchronous task completed")
return "Sync Result"
async def async_task():
print("Starting asynchronous task")
await asyncio.sleep(3) # Simulate a long-running async task
print("Asynchronous task completed")
return "Async Result"
def sync_callback(result):
if isinstance(result, Exception):
print(f"Sync Task Error: {result}")
else:
print(f"Sync Callback with result: {result}")
def async_callback(result):
if isinstance(result, Exception):
print(f"Async Task Error: {result}")
else:
print(f"Async Callback with result: {result}")
async def enqueue_async_task():
try:
result = await worker.enqueue_task_async(async_task)
print(f"Awaited Async Task Result: {result}")
except Exception as e:
print(f"Awaited Async Task Error: {e}")
def start_tasks():
# Enqueue synchronous task with callback
worker.enqueue_task(sync_task, callback=sync_callback)
# Enqueue asynchronous task with callback
worker.enqueue_task(async_task, callback=async_callback)
# Enqueue asynchronous task and await its result
asyncio.run_coroutine_threadsafe(enqueue_async_task(), worker.loop)
btn = tk.Button(root, text="Start Tasks", command=start_tasks)
btn.pack(pady=20)
def on_close():
worker.stop()
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_close)
root.mainloop()
if __name__ == "__main__":
main()
Explanation of the Implementation
-
ThreadWorker Class:
How to Use
-
Instantiate ThreadWorker:
worker = ThreadWorker(root) # 'root' is your Tkinter main window
-
Enqueue a Synchronous Task with a Callback:
def my_sync_func():
# Long-running synchronous task
return "Sync Task Completed"
def my_sync_callback(result):
print(result)
worker.enqueue_task(my_sync_func, callback=my_sync_callback)
-
Enqueue an Asynchronous Task with a Callback:
async def my_async_func():
# Long-running asynchronous task
await asyncio.sleep(2)
return "Async Task Completed"
def my_async_callback(result):
print(result)
worker.enqueue_task(my_async_func, callback=my_async_callback)
-
Enqueue and Await a Task:
async def main_task():
result = await worker.enqueue_task_async(my_async_func)
print(result)
asyncio.run_coroutine_threadsafe(main_task(), worker.loop)
-
Stopping the Worker:
Ensure you stop the worker when closing the application to clean up resources:
worker.stop()
Notes
- Thread Safety: The
callback_queue ensures that callbacks are safely passed to the Tkinter main thread.
- Error Handling: Exceptions in tasks are caught and passed to callbacks, allowing you to handle errors gracefully.
- Daemon Thread: The worker thread is marked as a daemon, meaning it won't block the program from exiting. However, it's good practice to stop it explicitly using the
stop method.
This implementation provides a flexible and efficient way to handle background tasks in a Tkinter application using asyncio, supporting both synchronous and asynchronous functions with callback mechanisms.