简体   繁体   中英

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).

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).

The result should then be stored in the tk variable calculated_value. I have bound this tk-variable to the option textvariable of a label.

Problem: The label does not display any text after executing the program. Can someone explain to me why the value that is in the calculated_value variable is not displayed via the 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. If you skip container , it defaults to the root 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 .

source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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