1

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()
unliimit
  • 29
  • 2
  • Did you try to change the Label's text when you change the variable's content? Or in the case where you change the variable (using ```tk.StringVar```), you should call another method to update like ```update_idletasks```. [Link of StackOverflow answer](https://stackoverflow.com/questions/2603169/update-tkinter-label-from-variable) – Carlos Adir Nov 23 '21 at 19:45
  • Does this answer your question? [tkinter Entry to StringVar() binding do not work](https://stackoverflow.com/questions/66713171/tkinter-entry-to-stringvar-binding-do-not-work) – frippe Nov 23 '21 at 20:03
  • Better use `Toplevel` instead of `Tk` for child windows. – acw1668 Nov 24 '21 at 03:34

1 Answers1

2

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

Random Davis
  • 6,662
  • 4
  • 14
  • 24