如何进行 Tkinter 标签更新? [英] How to make a Tkinter label update?

查看:39
本文介绍了如何进行 Tkinter 标签更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 tkinter GUI,带有一个显示数字和按钮的标签.我将它设置为变量 x,当按下按钮时,x 的值增加 1.但是,当我按下按钮时,标签不会更新.我该怎么做?

I have a simple tkinter GUI with a label displaying a number and a button. I have it set to the variable x, and when button is pushed, the value of x goes up by one. However, when I hit the button, the label doesn't update. How do I do this?

from tkinter import *

x = 1
def add():
    global x
    x += 1

win = Tk()

label = Label(win, text=x)
label.pack()

button = Button(win, text="Increment", command=add)
button.pack()

win.mainloop() 

推荐答案

配置标签的text 是一次性的效果.稍后更新 int 不会更新标签.

Configuring the text of a label is a one shot effect. Updating the int later won't update the label.

要解决这个问题,您可以自己显式更新标签:

To solve this, you can either explicitly update the label yourself:

def add():
    global x
    x += 1
    label.configure(text=x)

...或者您可以使用 tkinter 变量,就像 IntVar(或者更一般地说,一个 StringVar,如果你的文本不仅仅是一个数字),它会在你更新 var 时更新标签.如果您这样做,请不要忘记配置 textvariable 而不是 text.

... Or you can use a tkinter variable like an IntVar (or more generally, a StringVar, if your text isn't just a number), which does update the label when you update the var. Don't forget to configure textvariable instead of text if you do this.

from tkinter import *

win = Tk()

x = IntVar()
x.set(1)
def add():
    x.set(x.get() + 1)

label = Label(win, textvariable=x)
label.pack()

button = Button(win, text="Increment", command=add)
button.pack()

win.mainloop()

注意在创建 IntVar 之前创建 Tk() 实例 ,否则 tkinter 会抛出异常.

Take care to create a Tk() instance before you create the IntVar, otherwise tkinter will throw an exception.

这篇关于如何进行 Tkinter 标签更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆