Home > Blockchain >  How to DYNAMICALLY get the value of slider in Tkinter - Python
How to DYNAMICALLY get the value of slider in Tkinter - Python

Time:12-25

I need to get the value of the slider without tagging it to a button, which triggers a function to print the slider value.

from tkinter import *

#----function----#
def getVal():
    l1.config(text=("slider value = "   str(v1.get())))
    
#----UI-----#
root = Tk()
root.geometry("150x150")

v1 = DoubleVar()
s1 = Scale(root, variable=v1, from_=1, to=20, orient=HORIZONTAL)
s1.pack()

l1 = Label(root, text="0")
l1.pack()
b = Button(root, text="click to get val", command=getVal)
b.pack()

root.mainloop()

CodePudding user response:

You can attach a command to a slider, which will be called whenever the value changes. When the function is called, the new value is passed to the function.

def callback(new_value):
    l1.configure(text=f"The slider value is {new_value}")
...
s1 = Scale(..., command=callback)

CodePudding user response:

Does this help? Added two functions.

from tkinter import *


#----function----#
def getVal():
    return f'slider value ={v1.get(): .2f}'

def slider_changed(event):
    l1.configure(text=getVal())

def print_value():
    print(f'{v1.get()}')
    
#----UI-----#
root = Tk()
root.geometry("150x150")

v1 = DoubleVar()

s1 = Scale(root, from_=1, to=20,
           orient=HORIZONTAL,
           command=slider_changed,
           variable=v1) 
s1.pack()

l1 = Label(root, text=getVal())
l1.pack()

b = Button(root, text="click to get val", command=print_value)
b.pack()

root.mainloop()

Result screenshots before:

enter image description here

Result after trigger value:

enter image description here

  • Related