Get the value from a Tkinter scale and put it into a Label

TkinterPythonGUI-Programming

The Scale widget in tkinter allows you to create a visual scale slider object in your application which is used to specify the value using a specific scale. To implement the Scale object, you have to first create a constructor of Scale(root, **options). Here you can specify the properties and attributes of Scale such as command, background, label, length, orient, etc.

Since the Scale widget is used to select specific values by dragging the slider, we can get the current value of the scale in a label widget. To retrieve the value of the Scale, use the get() method that returns an integer value. In order to display the value in a Label widget, we can convert it into a string using string type casting.

Example

# Import required libraries
from tkinter import *

# Create an instance of tkinter window
win = Tk()
win.geometry("700x350")

# Define a function
def sel():
   selection= "Current Value is: " + str(var.get())
   label.config(text=selection)

# Create a scale widget
var=StringVar()
my_scale=Scale(win, variable=var, orient=HORIZONTAL,cursor="dot")
my_scale.pack(anchor = CENTER)

# Create a label widget
label=Label(win, font='Helvetica 15 bold')
label.pack()

# Create a button to get the value at the scale
button=Button(win, text="Get Value", command=sel)
button.pack()

win.mainloop()

Output

Running the above code will display a window with a scale slider to select a specific value in the range (0-100). Whenever you select a specific value, it will be just stored in a variable, which further can be used to display through a Label widget.

raja
Updated on 22-Dec-2021 10:55:40

Advertisements