[英]Python Tkinter: Why doesn't the label show the value of the tk variable that I bound to the label via the textvariable option?
简化的 Tkinter 应用程序应该执行以下操作:一旦您单击“在新窗口中打开计算器”按钮,另一个 tk window 应该打开(这有效)。
在这个新的 window 中,您还应该能够单击按钮开始计算(简化,我在计算中将两个数字加在一起)。
结果应存储在 tk 变量计算值中。 我已将此 tk 变量绑定到 label 的选项 textvariable。
问题:label 执行程序后不显示任何文本。 有人可以向我解释为什么计算值变量中的值没有通过 label 显示吗?
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.geometry("400x400")
def open_calculator_window():
window = tk.Tk()
window.geometry("200x200")
window.title("Calculator")
calculated_value = tk.StringVar(value="Placeholder")
def calculate_value():
try:
sum = 3.003 + 2.00000005
calculated_value.set("{:.3f}".format(sum))
print(calculated_value.get())
except ValueError:
print("ValueError")
value_label = tk.Label(window, text="Calculated Value")
value_label.pack()
euro_display = tk.Label(window, textvariable=calculated_value, bg="green")
euro_display.pack()
calculate_button = ttk.Button(window, text="Do Calculation", command=calculate_value)
calculate_button.pack(expand=True)
open_calculator_button = ttk.Button(root, text="Open Calculator in new Window", command=open_calculator_window)
open_calculator_button.pack()
root.mainloop()
StringVar 的第一个参数container
是与 StringVar object 关联的小部件。 如果你跳过container
,它默认为根 window。
您必须通过tk.StringVar(window, value="Placeholder")
设置 StringVar 的容器,因为它所在的 window 是window
,而不是root
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.