这是我目前的代码。
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
总是显示 num1
和 num2
. 然而,当我运行这段代码时, total_label
遗体 0
.
我怎么会有 total_label
相加 num1
和 num2
?
你可以在num1和num2上使用trace。
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)其中fun是一个函数,当num的值发生变化时就会被调用。 在fun函数中,你可以更新total的值。请看完整的 tkinter标签 教程。