'How to make a StringVar update its value when changing in tkinter?

import tkinter as tk
from tkinter import *
from math import *
from turtle import delay
from pylab import *
import time

my_w = tk.Tk()
my_w.geometry("200x500")  # Size of the window 
my_w.title("Puls")  # Adding a title

sv = StringVar() #string variable 
sb = Spinbox(my_w,textvariable=sv, width=15,from_=0,to=100)
sb.grid(row=1,column=1,padx=50,pady=10)

sc = Scale(my_w, from_=0, to=100,orient=HORIZONTAL,variable=sv)
sc.grid(row=2,column=1,padx=50)

def f(x): 
    return 0.45*x**3-8*x**2+52*x+66

x = float(sv.get())
y = f(x)

label = tk.Label(
    text=y,
    height=5
)

label.grid(row=3,column=1,padx=50)

label2 = tk.Label(
    text=x,
    height=5
)

label2.grid(row=4,column=1,padx=50)

my_w.mainloop()  # Keep the window open

I need to make the variable to change so my function actually works. How would I do this? Right now I think the code will work, but the variable x which is determined by a StringVar is only valued at one point the start.



Solution 1:[1]

You have to call sv.get() at the time you do the calculation, not before.

def do_func():
    x = float(sv.get())
    y = f(x)
    label.configure(text=y)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Karl Knechtel