我知道该函数适用于按钮,并且它确实获取数字,并且我可以打印 Num 变量,但是当我将其设置为输出字符串时,它似乎不会显示在输出文本中。我猜我在 output_str.set 函数或 textvariable 函数上做错了什么,但我不知道到底是什么。
顺便说一句,不会抛出任何错误
import tkinter as tk
def clicked():
num = (entry_int.get())
Num = num * 0.45
output_str.set = (Num)
window = tk.Tk()
window.title("Pounds to kilos")
window.geometry('350x200')
title = tk.Label(window, text = "Pounds to Kg", font = "helvectica" )
title.place(x = 115)
entry_int = tk.IntVar()
txt = tk.Entry(window, width = 15, textvariable = entry_int)
txt.place(x= 129, y= 30)
output_str = tk.StringVar()
output = tk.Label(window, fg = "blue", textvariable = output_str, font = "helvectic")
output.place(x= 126, y= 50)
btn = tk.Button(window, text = "Calculate",fg = "red", command = clicked )
btn.place(x = 240, y = 26)
window.mainloop()
我测试了输出文本并测试它实际上正在获取输入数字。
我期望 Num 变量显示在输出标签中
您没有正确更新
StringVar
。使用 output_str.set = (Num)
代替 output_str.set(Num)
。这是固定的 clicked()
函数:
def clicked():
num = int(entry_int.get()) # Convert input to integer
Num = num * 0.45
output_str.set(Num) # Update StringVar with the calculated value