How to Get Value from Spinbox in Tkinter

One of the widgets that Tkinter provides is the Spinbox

The Spinbox widget allows you to select a value from a fixed range of numbers or a list of values. We will learn how to create a Spinbox widget and how to get the value that the user has selected.

Creating a Spinbox Widget

To create a Spinbox widget, start by importing Tkinter and initializing a root window:

import tkinter as tk

root = tk.Tk()

Use the tk.Spinbox constructor with options such as from_, to, values, textvariable, and command to create and customize your Spinbox widget.

See also  Creating a Multi-Select Drop-Down List in Tkinter

For a numeric range Spinbox:

spin_value = tk.StringVar(value=1)
spin_box = tk.Spinbox(root, from_=1, to=10, textvariable=spin_value)
spin_box.pack()

For a list of values Spinbox:

colors = ("Red", "Green", "Blue", "Yellow", "Pink")
spin_value = tk.StringVar(value=colors[0])
spin_box = tk.Spinbox(root, values=colors, textvariable=spin_value)
spin_box.pack()

Getting the Value from a Spinbox Widget

To retrieve the selected value, use either the get() method of the tk.StringVar object or the Spinbox widget itself.

print(spin_value.get())  # Using tk.StringVar
print(spin_box.get())    # Directly from Spinbox widget

To convert the value to a different data type:

num = int(spin_box.get())
print(num + 1)

Executing a Function When the Value Changes

Use the command option to specify a function to execute on value change. For example, to change the background color:

def change_color():
    color = spin_value.get()
    root.config(bg=color)

spin_box = tk.Spinbox(root, values=colors, textvariable=spin_value, command=change_color)

This setup allows the root window’s background color to change according to the selected color in the Spinbox widget.

See also  Effortlessly Select Files with Tkinter's askopenfilename