Tkinter, threads, mainloops, etc

Harald Hanche-Olsen hanche at math.ntnu.no
Sun Jan 23 13:42:25 EST 2000


I have a program that does some numerical computation on a time
dependent problem.  I'd like for the program to create some graphics,
updating it as it goes along, to visualise the results.  Up to now I
have used a really crude method, but one that works:  I open a pipe to
a ghostscript interpreter and send raw postcript commands down the
pipe.

I'd like to use Tkinter instead, in order to take advantage of some of
the higher order functionality available.  However, I still want to
have the python command prompt available, which I wouldn't if I called
the root window's mainloop().

I saw a message a while back, suggesting a separate thread to do event
handling, so I can keep the interactive interpreter in the main
thread.  Can someone provide some hints on how to do that in practice?
Maybe a pointer to some code that does it?

Actually, I have nearly come to believe that mainloops aren't
necessary at all.  Perhaps naively, I thought events would not be
handled at all until I run a mainloop, but the following experiment
shows that callbacks are indeed called even when no mainloop is
running:

Python 1.5.2 (#2, Nov 19 1999, 23:01:49)  [GCC 2.7.2.3] on freebsd3
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import Tkinter, whrandom
>>> def timbot(): print '<%.2f wink>' % whrandom.random()
.. 
>>> root = Tkinter.Tk()
>>> Tkinter.Button(root, text='Spam', command = timbot).pack()
>>> Tkinter.Button(root, text='Quit', command = root.destroy).pack()
>>> # Here I start hitting the Spam button
<0.95 wink>
<0.51 wink>
<0.88 wink>
<0.26 wink>

I can resize the window too, and the buttons get rearranged
accordingly.  So what is a mainloop good for, anyway?

(Also, would I get different advice if I were to run my program from
within IDLE?  That would certainly be no great hardship at all - I
just now started playing with it, and I have already more or less
abandoned py-shell in emacs.)

Confused-about-how-tkinter-really-hangs-together-ly y'rs,
-- 
* Harald Hanche-Olsen     <URL:http://www.math.ntnu.no/~hanche/>
- "There arises from a bad and unapt formation of words
   a wonderful obstruction to the mind."  - Francis Bacon



More information about the Python-list mailing list