更新 python Tkinter 框架 [英] Updating a python Tkinter frame
问题描述
我在更新 python Tkinter 框架时遇到困难.我画框一些标签和文本字段,当一个人按下按钮时,我想做一些计算并更新标签和文本字段.我可以将数据打印到我的标准输出,但我无法更新 Tk 屏幕.如何让 countFld 显示更新的值?
I am having difficulty updating a python Tkinter frame. I draw the frame with some labels and text fields, when a person presses a button, I want to do some calculations and update the labels and text fields. I can print the data to my stdout, but I cannot get the Tk screen to update. How can I get the countFld to display an updated value?
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
推荐答案
您的问题是您没有将变量附加到小部件.此外,您需要使用 StringVar,因为 Label Widget 对 Strings 而不是 Ints 进行操作.
Your problem is that you do not attach the Variable to the widget. In addition you need to use a StringVar, as the Label Widget operates on Strings and not Ints.
尝试类似:
self.countStr = StringVar()
self.countStr.set(str(self.count))
Label(self.countFrame, textvariable=self.countStr).pack(side=RIGHT, padx=5)
Tk 在 eventloop 空闲时更新显示.所以设置新值后需要重新进入事件循环.
Tk updates the display when the eventloop is idle. So you need to re-enter the event loop after you set the new value.
这篇关于更新 python Tkinter 框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!