Tkinter: Any way to flush events without blocking?
Russell E. Owen
no at spam.invalid
Tue Feb 24 19:39:51 EST 2004
In article <c9d82136.0402241037.69be029a at posting.google.com>,
noah at noah.org (Noah) wrote:
>I have a long running application with a Tkinter GUI.
>Is there a way to see how many events are pending in the queue?
>I want my application to occasionally process events (so that the
>output window will update; the root window will refresh if
>the user moves it; etc.).
>
>I tried using Tk.tk.dooneevent(), but it blocks if no events are
>available. What I thought of doing is calling a method that
>does something like this:
> # event_queue_empty() does not exist
> while not root.tk.event_queue_empty():
> root.tk.dooneevent(0)
I think this is what you want:
tk_object.update_idletasks()
>The problem is that I'm calling an imported Python method
>that runs for a long time. I can't easily retrofit it into an
>event-oriented application.
...
>I suppose that my other option is to use a thread, but that
>seems overkill when all I want is a updated window.
update_idletasks() will do what you want.
But you might want to consider a thread anyway. This would be especially
nice if there is any way to add code to the long-running task that would
check to see if the user had aborted. In that case having a thread means
you could implement a responsive "Cancel" button. As far as
communicating from the thread to the main task, there are several
options, including:
- Have the background thread write its output to a Queue and poll the
Queue with an after() loop. This is dirt simple, though a bit
inefficient.
- Have the background thread create an event. Bind a callback to that
event. The callback will run in the main loop, so is safe for writing to
Tk widgets. I read about this neat trick recently on this news group.
(Whatever you do, don't have the background thread try to write to Tk
widgets or set Tk variables. But I assume you know that.)
-- Russell
More information about the Python-list
mailing list