Tuesday, April 22, 2025

Tkinter - Scale

This source will produce simple Tkinter GUI with horizontal scale on it, in value range from 1 to 100, using label "Range". 

Scale will be packed to center of the top_win. At the bottom of the scale we will have submit Button. 

No functions at the moment, just GUI:

from tkinter import *
import tkinter.messagebox as mb
import os

top_win = Tk()
top_win.geometry("800x800")

scale = Scale(top_win, label = "Range", from_ = 1, to = 100,
              orient = HORIZONTAL)
scale.pack(anchor = CENTER)

btn_1 = Button(top_win, text = "Submit")
btn_1.pack(anchor = CENTER)

top_win.mainloop()

So, a source to create scale is this one:

scale = Scale(top_win, label = "Range", from_ = 1, to = 100,
              orient = HORIZONTAL)
scale.pack(anchor = CENTER)

What about a source with function that will print something on Python Shell based on values from Scale:

from tkinter import *
import tkinter.messagebox as mb
import os

top_win = Tk()
top_win.geometry("800x800")

def select():
    selected = real_val.get()
    print("Selected From Range: ", selected)

    if selected >= 50:
        print("More Than 50")

real_val = IntVar()

scale = Scale(top_win, label = "Range", length = 200, from_ = 1, to = 100,
              orient = HORIZONTAL, troughcolor = "red", variable = real_val)
scale.pack(anchor = CENTER)

btn_1 = Button(top_win, text = "Submit", command = select)
btn_1.pack(anchor = CENTER)

top_win.mainloop()

Function select() will get and check a point from scale. That value will be printed in Python Shell.

Also, if value is higher than 50, that will be printed too.

def select():
    selected = real_val.get()
    print("Selected From Range: ", selected)

    if selected >= 50:
        print("More Than 50")

Value is stored in real_val using this line:

real_val = IntVar()

To connect scale with real_val, use these lines:

scale = Scale(top_win, label = "Range", length = 200, from_ = 1, to = 100,
              orient = HORIZONTAL, troughcolor = "red", variable = real_val)
scale.pack(anchor = CENTER)

At the end we need to connect a button with function, using "command = ":

btn_1 = Button(top_win, text = "Submit", command = select)
btn_1.pack(anchor = CENTER)

There is corresponding YouTube tutorial on Tkinter Scale.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...