Use threads or Tkinter event loop?

Kevin Walzer kw at
Tue Mar 27 16:05:22 CEST 2007

I'm trying to decide whether I need threads in my Tkinter application or 
not. My app is a front end to a command-line tool; it feeds commands to 
the command-line program, then reads its output and displays it in a 
Tkinter text widget. Some of the commands are long-running and/or return 
thousands of lines of output.

I initially thought I needed to use threading, because the GUI would 
block when reading the output, even when I configured the blocking to be 
non-blocking. I got threading to work, but it seemed a bit complicated. 
So, I decided to try something simpler, by using the Tkinter event loop 
to force the output to update/display.

it seems to work well enough. Here is my threaded code:


def insertDump(self):
  self.finkinstalled = os.popen('/sw/bin/fink list', 'r', os.O_NONBLOCK)
         for line in self.finkinstalled:
             self.t.insert(END, line)

And here is my non-threaded code (needs two functions to work)

  def insertDump(self):
             data = self.dataQueue.get(block=False)
             for line in data:
                 self.t.insert(END, line)

             print "error"

     def getDump(self):

         self.file = os.popen('/sw/bin/fink list', 'r', os.O_NONBLOCK)

This brings me to a design, as opposed to coding, question. The 
non-threaded version seems to work just as well as the threaded one, in 
terms of speed. Moreover, it is simpler to code and debug, because I 
don't have to check to make sure the thread queue has data (I sometimes 
get an 'Empty' error message when I first start the thread).  Simply 
using the Tk event loop (self.update) is also how I would have coded 
this in Tcl.

So my question is this: under what circumstances in Python are threads 
considered "best practice"? Am I wrong to use the Tk event loop instead 
of threads?

Kevin Walzer
Code by Kevin

More information about the Python-list mailing list