python - 更新 python Tkinter 框架

标签 python tkinter

我在更新 python Tkinter 框架时遇到困难。我画框架 一些标签和文本字段,当一个人按下按钮时,我想做一些 计算并更新标签和文本字段。我可以将数据打印到我的 stdout,但我无法更新 Tk 屏幕。如何让 countFld 显示更新的值?

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 对字符串而不是整数进行操作。

尝试如下:

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

Tk 在事件循环空闲时更新显示。所以设置新值后需要重新进入事件循环。

关于python - 更新 python Tkinter 框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5362404/

相关文章:

python - Count 满足条件的序列总数,无 for 循环

python - strptime 和 strftime 中参数的不同顺序

python - 如何在 C 中创建 Python 类?

python - 为什么在切换到 python3 时从 python 内置函数中删除了重新加载?

python - 将直方图放入 tkinter 框架中

excel - Python——将字符串添加到剪贴板,以正确的格式粘贴到 Excel(即,分隔为行/列)

python - 为python安装最新版本的aubio

python - Tkinter 输入框,不允许一次输入和显示一个字符串

python - 使用 tkinter 创建椭圆形的流畅运动

python - tkinter 强制缩进