2011-03-19 98 views
2

我很难更新python的Tkinter框架。我用 画一些标签和文本字段,当一个人按下一个按钮时,我想要做一些 计算并更新标签和文本字段。我可以将数据打印到我的 stdout,但我无法获取Tk屏幕进行更新。我怎样才能让countFld显示更新的值?更新python的Tkinter框架

class Application(Frame): 

    def __init__(self): 
     self.root = Tk() 
     Frame.__init__(self, self.root) 
     self.count = 0 
     self.createWidgets() 

    def createWidgets(self): 
     self.countFrame = Frame(self, bd=2, relief=RIDGE) 
     Label(self.countFrame, text='Count:').pack(side=LEFT, padx=5) 
     self.countFld = IntVar() 
     Label(self.countFrame, text=str(self.count)).pack(side=RIGHT, padx=5) 
     self.countFld.set(self.count) 
     self.countFrame.pack(expand=1, fill=X, pady=10, padx=5) 

     self.CNTBTN = Button(self) 
     self.CNTBTN["text"] = "UPDATE" 
     self.CNTBTN["fg"] = "red" 
     self.CNTBTN["command"] = self.update_count 
     self.CNTBTN.pack({"side": "left"}) 

    def update_count(self): 
     self.count = self.count + 1 
     print "Count = %" % self.count #prints correct value 
     self.countFld.set(self.count) #Does not update display 

回答

2

你的问题是你不把变量附加到小部件。此外,您需要使用StringVar,因为Label Widget在字符串上操作而不在Ints上操作。

尝试类似:

self.countStr = StringVar() 
self.countStr.set(str(self.count)) 
Label(self.countFrame, textvariable=self.countStr).pack(side=RIGHT, padx=5) 

Tk的更新显示,当事件循环处于闲置状态。因此,您需要在设置新值后重新进入事件循环。