Search code examples
pythonvariablestkinter

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

  • You can use sv.trace_add(...) to execute a function whenever the value of sv is changed:

    ...
    
    # used to show the result of f(x)
    label = tk.Label(height=5)
    label.grid(row=3, column=1, padx=50)
    
    # used textvariable=sv to show the 'x' value
    label2 = tk.Label(textvariable=sv, height=5)
    label2.grid(row=4, column=1, padx=50)
    
    def on_change(*args):
        x = float(sv.get())
        y = round(f(x), 2)  # change 2 to whatever value you want
        label.config(text=y)
    
    sv.trace_add('write', on_change) # call on_change() whenever sv is changed
    on_change() # show initial result
    
    my_w.mainloop()