import threading import contexts class TkContext(contexts.CallableContext): def __init__(self, app): self.app = app self._post_signal = threading.Condition() @staticmethod def invoke(callable, args, kwargs): callable(*args, **kwargs) @staticmethod def invoke_and_notify(signal, callable, args, kwargs): with signal: callable(*args, **kwargs) signal.notify_all() def post(self, callable, *args, **kwargs): '''Adds a callable to invoke within this context.''' self.app.after(0, TkContext.invoke, callable, args, kwargs) def submit(self, callable, *args, **kwargs): '''Adds a callable to invoke within this context and returns when it has been completed. ''' with self._post_signal: self.app.after(0, TkContext.invoke_and_notify, self._post_signal, callable, args, kwargs) self._post_signal.wait()