While loop and time.sleep function
Brian Kelley
bkelley at wi.mit.edu
Fri Feb 22 09:44:41 EST 2002
Alves, Carlos Alberto - Coelce wrote:
> Hi all,
> I tray to make a simple clock program ( see the code below ).
> Can someone explain to me why code 01 works while code 02 doesn't
>
You almost never want to use things like time.sleep in Tkinter apps
since Tkinter is single threaded. This means while time.sleep is
sleeping, the gui window will not be updated.
It is much safer to use things like
root.after(milliseconds, function)
to set up timers like you want. You might want to read Lundh's
introduction to Tkinter at:
http://www.pythonware.com/library/tkinter/introduction/index.htm
Here is a Clock class that uses the .after timer
import time
class Clock:
def __init__(self,root):
self.root = root
self.lb=Label(root,padx=5,pady=5,
fg='blue',font=('Times',20))
self.lb.pack()
self.root.after(1000, self.ck)
self.ck()
def ck(self):
self.lb.configure(text=time.asctime()[11:19])
# set up the next callback
self.root.after(1000, self.ck)
if __name__ == "__main__":
from Tkinter import *
root = Tk()
root.title('Clock')
Clock(root)
mainloop()
Brian Kelley
More information about the Python-list
mailing list