简体   繁体   English

Python Z6F8BBBEA5A81184EBA8B78919F51A600DZ:为什么ZD304BA204BA20E96D87411588EEABAC84EBY DEBAR INDENBBAR STOBLIAL STOM INDEN 888888888888888888080号tk

[英]Python Tkinter: Why doesn't the label show the value of the tk variable that I bound to the label via the textvariable option?

The simplified Tkinter application should do the following: as soon as you click on the "Open Calculator in new window" button, another tk window should open (this works).简化的 Tkinter 应用程序应该执行以下操作:一旦您单击“在新窗口中打开计算器”按钮,另一个 tk window 应该打开(这有效)。

In this new window you should also be able to click a button to start a calculation (simplified, I added two numbers together in the calculation).在这个新的 window 中,您还应该能够单击按钮开始计算(简化,我在计算中将两个数字加在一起)。

The result should then be stored in the tk variable calculated_value.结果应存储在 tk 变量计算值中。 I have bound this tk-variable to the option textvariable of a label.我已将此 tk 变量绑定到 label 的选项 textvariable。

Problem: The label does not display any text after executing the program.问题:label 执行程序后不显示任何文本。 Can someone explain to me why the value that is in the calculated_value variable is not displayed via the 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()

The first argument to StringVar, container , is the widget that the StringVar object associated with. StringVar 的第一个参数container是与 StringVar object 关联的小部件。 If you skip container , it defaults to the root window.如果你跳过container ,它默认为根 window。

You have to set the container of your StringVar via tk.StringVar(window, value="Placeholder") , because the window it's in is window , not root .您必须通过tk.StringVar(window, value="Placeholder")设置 StringVar 的容器,因为它所在的 window 是window ,而不是root

source资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM