Tkinter window displaying the time?

Jeff Shannon jeff at ccvcorp.com
Mon Aug 27 13:46:40 EDT 2001


Gary Richardson wrote:

> Is is possible to do this in a thread? I.e.:
>
> from Tkinter import *
> from time import *
> import thread
>
> def titleTime():
>     now = strftime("GMT: %I:%M:%S %p", localtime(time()))
>     #root.title(now)
>     root.after(1000, titleTime)
>
> root=Tk()
> root.iconify()
> thread.start_new(titleTime, ())
> root.mainloop()
>
> When I uncomment the line "root.title(now)" this code hangs up and I have to
> exit the IDE to recover. I'm using PythonWin, ActivePython build 2.1.211.

When writing multithreaded apps under a GUI, it is generally a bad idea to try
to have multiple threads interacting with the GUI objects.  The proper
architecture for multithreaded GUIs is to have one thread handle *all* of the
GUI activity, and delegate calculations or other long processes to worker
threads.  In this case, you're really not gaining anything by putting your timer
function in a separate thread--what you're trying to accomplish, is already
being done by calling after(), so threading it is redundant.  If you *were*
going to change some UI feature based on some involved calculation, that you
wanted to move to a separate thread, then you could use the worker thread to
update a shared variable, and have the UI thread poll that variable (using
after() or such) and update the feature when the variable changes.
Alternatively, you could use a Queue to allow worker threads to pass
commands/data to the UI thread (this is actually just a more detailed, robust
version of the previous--the queue is the "shared variable").

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list