简体   繁体   English

如何更新Tkinter标签?

[英]How to make a Tkinter label update?

I have a simple tkinter GUI with a label displaying a number and a button. 我有一个简单的tkinter GUI,带有显示数字和按钮的标签。 I have it set to the variable x, and when button is pushed, the value of x goes up by one. 我把它设置为变量x,当按下按钮时,x的值增加1。 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() 

Configuring the text of a label is a one shot effect. 配置标签的text是一键式效果。 Updating the int later won't update the label. 稍后更新int不会更新标签。

To solve this, you can either explicitly update the label yourself: 要解决此问题,您可以自己显式更新标签:

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

... 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. ...或者您可以使用tkinter变量,例如IntVar (或更IntVarStringVar ,如果您的文本不只是数字), 在更新var时会更新标签。 Don't forget to configure textvariable instead of text if you do this. 如果这样做,请不要忘记配置textvariable而不是text

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()

Take care to create a Tk() instance before you create the IntVar , otherwise tkinter will throw an exception. 创建IntVar 之前,IntVar 创建一个Tk()实例,否则tkinter会引发异常。

You have to do it manually by associating a command with the click of the button. 您必须通过将command与单击按钮相关联来手动完成。 Suppose you want the text of the Label to update when you click button : 假设您希望单击button时更新Label的文本:

button = Button(win, text="One", command=add) # add() is called when button is clicked

Now, you define the add command/function in order to change the text in the label: 现在,您定义add命令/函数以更改标签中的文本:

def add():
    global x
    x += 1
    label.config(text=x) # calling the method config() to change the text

What I did is to use a IntVar() and a method to add or subtract: 我做的是使用IntVar()和方法来加或减:

*outside the class body*
def plus1(self,var,l):
    var.set(int(var.get())+1)
    l.textvariable = var
    return var.get()

*Inside the body of your class*
self.your_text = IntVar()
self.your_text.set(0)

self.l = Label(master, textvariable = (self.your_text))
self.plus_n = Button(root,text = '+',command=lambda : self.your_text.set(self.plus1(self.your_text,self.l) ) 

This is how I did it and it works for me, probably there are more elegant ways to solve the problem 这就是我做到的,它对我有用,可能有更优雅的方法来解决问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM