My Tkinter Threading nightmare

Paul Rubin http
Thu Jan 25 04:11:59 CET 2007


half.italian at gmail.com writes:
> and setup the callback to kill the operation and then the window when
> the user clicks on the X of the progress window.  I've implemented this
> in my code, but clicking on the X does nothing until I kill the main
> thread (i think), and then my callback is run.  I've also had problems
> in the past of the gui not refreshing properly, which leads me to
> believe that both of these are thread related.  Any help would be
> immensely appreciated.

That was more code than I was willing to sit and read, but basically
the tkinter thread blocks unless there's tkinter events.  The usual
trick for what you're trying to do is to set up a tk.after event to
run every 20 msec or so.  That can check for commands on a queue to
launch operations, kill windows, or whatever.  In your Window class
you'd have something like (this is pseudocode, I don't remember the
exact params and args off the top of my head so you'll have to check
them):

      def __init__(self, ...):
         ...
         self.after(20, self.idle)

      def idle(self):
         # read and execute any commands waiting on the queue
         while True:
            try:
               func, args, kw = self.cmd_queue.get(block=False)
            except QueueEmpty:
               return
            func (*args, **kw)

cmd_queue is a queue that you set up ahead of time, and you use it to
send commands into your gui thread from other threads, such as window
kill.  Don't call gui functions directly as tkinter is not
thread-safe.



More information about the Python-list mailing list