Python - GUI Programming - Spinbox Widget

A Spinbox is a widget in Python's Tkinter library, which allows the user to select a value from a predefined range of values. It is also known as a Spin Entry, which means it is a combination of a Spinbox and an Entry widget. The Spinbox widget consists of two small buttons that allow the user to increment or decrement the selected value.

In this tutorial, we will learn how to create a Spinbox widget, set its properties, and use it in a Python application.

Creating a Spinbox Widget:

To create a Spinbox widget, we first need to import the Tkinter module:

from tkinter import *

Next, we can create an instance of the Tk class to create a top-level window:

root = Tk()

After that, we can create a Spinbox widget using the Spinbox class:

spinbox = Spinbox(root, from_=0, to=10)

The from_ and to arguments define the range of values that can be selected in the Spinbox.

Setting Spinbox Properties:

There are various properties that we can set for the Spinbox widget, including the width, font, and state. We can set these properties using the config() method.

Here is an example of how to set the width and font properties of the Spinbox:

spinbox.config(width=5, font=('Arial', 12))

We can also set the state property of the Spinbox to "readonly", which means that the user can only select values from the given range, and cannot enter any other value:

spinbox.config(state='readonly')

Using the Spinbox Widget:

To get the currently selected value from the Spinbox widget, we can use the get() method:

selected_value = spinbox.get()

We can also set the currently selected value in the Spinbox using the set() method:

spinbox.set(5)

Here's an example application that demonstrates the use of the Spinbox widget:

from tkinter import *
root = Tk()
root.title("Spinbox Example")
spinbox = Spinbox(root, from_=0, to=10)
spinbox.config(width=5, font=('Arial', 12))
spinbox.config(state='readonly')
spinbox.pack(pady=10)
def show_selected_value():
    selected_value = spinbox.get()
    label.config(text=f"Selected Value: {selected_value}")
button = Button(root, text="Show Selected Value", command=show_selected_value)
button.pack(pady=10)
label = Label(root, text="")
label.pack(pady=10)
root.mainloop()

In this example, we create a top-level window and a Spinbox widget with a range of values from 0 to 10. We set the width, font, and state properties of the Spinbox, and then display it on the window.

We also create a button that, when clicked, retrieves the currently selected value from the Spinbox and displays it in a label.