A smallish Tkinter question

Kent Johnson kent37 at tds.net
Thu Apr 21 11:29:15 EDT 2005


mediocre_person at hotmail.com wrote:
> """
> What I want: A little window to open with a 0 in it. Every second, the
> 0 should increment by 1.
> What I get: A one second delay, see the window with a 1 in it, and then
> nothing appears to happen. Never see the 0, never see a 2.  Any quick
> clues? Thanks. Nick. (Python 2.4, Win98).

Your run() method doesn't loop, so it only updates once. But there is a fundamental problem; the 
run() method is called before you even start Tkinter by calling mainloop(). That's why you never see 
the 0. If you change run to loop forever, it won't return and you will never even get to the 
mainloop() call.

Tkinter supports timed, asynchronous callbacks. Here is a program that uses a callback to display a 
ticker:
from Tkinter import *

count = 0

def update():
     ''' Callback method updates the label '''
     global count
     count += 1
     label.configure(text=str(count))

     # Schedule another callback
     root.after(1000, update)


root=Tk()
label=Label(root,text="0")
label.pack()

b=Button(root,text="Bye",command='exit')
b.pack()

# Schedule the initial callback
root.after(1000, update)

root.mainloop()


Kent
> """
> 
> from Tkinter import *
> from time import sleep
> 
> class Clock:
>     def __init__(self, parent):
>         self.time = 0
>         self.display = Label(parent)
>         self.display["font"] = "Arial 16"
>         self.display["text"] = str(self.time)
>         self.display.pack()
> 
>     def run(self): #also tried self,parent
>         sleep(1.0)
>         self.time = self.time + 1
>         self.display["text"] = str(self.time)
> 
> win = Tk()
> app = Clock(win)
> app.run() #also tried run(win) with self,parent above
> win.mainloop()
> 



More information about the Python-list mailing list