update tkinter window
Chad Netzer
cnetzer at mail.arc.nasa.gov
Thu Nov 14 18:08:36 EST 2002
On Thursday 14 November 2002 13:59, Roger wrote:
> I've been messing with tkinter a little.
> I was trying to just come up with a window that would show the current
> time.
> stealing some code from examples, I came up with:
[snipped]
Here is my quick rewrite which probably does what you want:
from time import localtime, strftime
from Tkinter import *
class myclock(Frame):
def update_stats(self):
self.contents.set(strftime("%H:%M:%S",localtime()))
self.after(self.msecs, self.update_stats)
return
def __init__(self, msecs=1000):
Frame.__init__(self)
self.msecs=msecs
self.contents=StringVar()
self.entry=Entry(textvariable=self.contents)
self.entry.pack()
self.update_stats()
return
m = myclock( msecs=1000 )
m.pack()
m.mainloop()
> ------------------------------------------------------------
> the problem is the window keeps adding a new time making the window ever
> increasing in size.
Because you were calling pack() in the update_stats() method, which caused it
to pack again. You could have forgot() the widget first, and then packed it,
but that was unnecessary. As you see, I packed the Entry in the __init__, so
that it only occurs *once* when 'myclock' is created, and so doesn't pack
repeatedly in the Frame.
Some notes:
I also create the Entry to refer to the StringVar immediately. Then,
whenever you update the StringVar, using set, the Entry widget automatically
updates.
It is almost *NEVER* a good idea for a widget to pack() itself in its own
__init__ method. It is error prone, and makes it hard to reuse your widget.
When you subclass Frame, you are saying that your new class *IS* a Frame, and
will behave like a Frame (and could be used everywhere a Frame is used).
Frames do not pack() themselves, and neither should you. The code that
creates myclock() should pack it (or grid it, etc.), like it would any other
frame. (when I started with Tkinter, I did the same thing as you, and had to
painfully unlearn that technique)
--
Bay Area Python Interest Group - http://www.baypiggies.net/
Chad Netzer
cnetzer at mail.arc.nasa.gov
More information about the Python-list
mailing list