Saturday, June 05, 2010

[Py] Update label's content

I am writing a simple program in Python with Tkinter, and got troubles when I wanted to update the text showed in the label. I have a variable which has been changed in certain function and I want to show its latest value on a label of the root window.

Before I find the solutions, I think all I need are Label.config() and time.sleep(). However, they didn't make the program run as what I expected.

Finally, I found the key is the update() function. There are two ways to do what I want, but I don't know the differences between them. Let me just show the test programs I've written.

[label_test1.py]
from Tkinter import *
import time

class App:
def __init__(self, master):

frame = Frame(master).pack()
master.geometry("200x100")

var_text = StringVar()
counter = Label(frame)
counter.config(textvariable=var_text, font=("arial",60,"bold"), bg="green")
counter.pack(expand=YES, fill=BOTH)

for i in range(10):
time.sleep(1)
var_text.set(i)
master.update()

def main():
root = Tk()
app = App(root)
root.mainloop()

if __name__ == "__main__":
main()


[label_test2.py]
from Tkinter import *
import time

class App:
def __init__(self, master):

frame = Frame(master).pack()
master.geometry("200x100")

counter = Label(frame)
counter.config(font=("arial",60,"bold"), bg="green")
counter.pack(expand=YES, fill=BOTH)

for i in range(10):
time.sleep(1)
counter.config(text=i)
master.update()

def main():
root = Tk()
app = App(root)
root.mainloop()

if __name__ == "__main__":
main()

---
Ref:

No comments:

Post a Comment