如何更新 Tkinter 标签小部件?

How to update Tkinter Label widget?

到目前为止,这是我的代码:

from tkinter import *

root = Tk()

num1 = IntVar()
num2 = IntVar()

total = IntVar()
total.set(num1.get() + num2.get())

entry1 = Entry(root, textvariable = num1)
entry1.pack()

entry2 = Entry(root, textvariable = num2)
entry2.pack()

total_label = Label(root, textvariable = total)
total_label.pack()

我想要做的是让 total_label 始终显示 num1num2 的总和。但是,当我 运行 代码时, total_label 仍然是 0.

如何让 total_label 显示 num1num2 的总和?

您可以在 num1 和 num2 上使用跟踪:

from tkinter import *

root = Tk()

num1 = IntVar()
num2 = IntVar()
total = IntVar()
def update_total(*severalignoredargs):
    total.set(num1.get() + num2.get())

num1.trace('w',update_total)
num2.trace('w',update_total)


entry1 = Entry(root,textvariable=num1)
entry1.pack()

entry2 = Entry(root,textvariable=num2)
entry2.pack()

total_label = Label(root,textvariable=total)
total_label.pack()

root.mainloop()

您应该做的是对文本变量调用跟踪方法。喜欢 num.trace('w', 有趣) 其中 fun 是每当 num 的值发生变化时调用的函数。在 fun 函数中,您可以更新 total 的值。查看完整的 tkinter label 教程。