我正在尝试创建一个标签,该标签会自动显示输入变量的结果。 基本上,我正在尝试将这两个程序结合起来:
from tkinter import *
root = Tk()
var = StringVar()
var.set('hello')
l = Label(root, textvariable = var)
l.pack()
t = Entry(root, textvariable = var)
t.pack()
root.mainloop() # the window is now displayed
该标签(来源:Update Tkinter Label from variable)会自动更新标签,但是只能将其更新为用户输入的标签。
和这个:
from tkinter import *
myWindow = Tk()
def MyCalculateFunction():
pressure, temprature = float(box_pressure.get()), float(box_temprature.get())
result = pressure + temperature
label_result.config(text="%f + %f = %f" % (pressure, temprature, result))
box_pressure = Entry(myWindow)
box_pressure.pack()
box_temprature = Entry(myWindow)
box_temprature.pack()
button_calculate = Button(myWindow, text="Calcuate", command=MyCalculateFunction)
button_calculate.pack()
label_result = Label(myWindow)
label_result.pack()
我遇到的问题是,如果用户更改压力或温度,结果不会自动更改。 (来源:How to get value from entry (Tkinter), use it in formula and print the result it in label)
如何做到这一点,以便当用户更改任何变量时,Python自动计算新结果并自行更改标签?
答案 0 :(得分:1)
您错过了几件事。
Tkinters小部件需要变量来保存输入到其中的值,而在温度和压力小部件中创建时会错过这些变量。
最好为您计算值,然后set
小部件变量。
希望这会有所帮助。
from tkinter import *
myWindow = Tk()
def MyCalculateFunction():
label_variable=StringVar()
label_result= Label(myWindow, textvariable=label_variable)
label_result.pack()
pressure, temperature = float(pressure_variable.get()), float(temperature_variable.get())
result = pressure + temperature
label_variable.set("%f + %f = %f" % (pressure, temperature, result))
pressure_variable=StringVar()
box_pressure = Entry(myWindow, textvariable=pressure_variable)
box_pressure.pack()
temperature_variable=StringVar()
box_temprature = Entry(myWindow, textvariable=temperature_variable)
box_temprature.pack()
button_calculate = Button(myWindow, text="Calcuate", command=MyCalculateFunction)
button_calculate.pack()