While loop and time.sleep function
Eric Brunel
eric.brunel at pragmadev.com
Thu Feb 21 14:42:03 EST 2002
Hi,
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
[snip]
Eeer, in fact both codes didn't work... At least on my Linux box. The first
problem is that there is no mainloop, so Tk never actually starts. The
second problem is that since the control never returns to Tk (because of
the "while 1"), Tk never gets a chance to refresh the display. So you must
explicitely refresh it manually:
-----------------------
from Tkinter import *
import time
class Clock:
def __init__(self,root):
self.lb=Label(root,padx=5,pady=5,fg='blue',font=('Times',20))
self.lb.pack()
self.ck()
self.update()
def ck(self):
self.lb.configure(text=time.asctime()[11:19])
# Refresh the display; otherwise, nothing happens...
self.lb.update_idletasks()
def update(self):
while 1:
self.ck()
time.sleep(1)
if __name__=='__main__':
root=Tk()
root.title('Clock')
Clock(root)
# Run Tk main loop
root.mainloop()
-------------------------------
HTH
- eric -
More information about the Python-list
mailing list