tkinter
  1. tkinter-spinbox

Spinbox Input Widget in Tkinter

Spinbox is a widget in Tkinter, Python's standard GUI library, that allows users to input a value by selecting from a range of predefined values using an increment/decrement button support. Spinbox helps to maintain a limited range of values as specified by the user.

Syntax

The syntax for creating a Spinbox widget in Tkinter is as follows:

spinbox = tk.Spinbox(window, from_= start, to=stop, increment=increment_value, font=my_font, foreground=my_color, command=my_function)

Here,

  • window: The parent window in which the widget will be placed.
  • from_ : The minimum value of the range.
  • to: The maximum value of the range.
  • increment: The value by which the component changes with one push of the up or down button.
  • font: Font style of the text displayed in the spinbox window.
  • foreground: Text color of the spinbox window.
  • command: The function that will be called when the spinbox value changes.

Example

import tkinter as tk

def selection():
    var = "Selected value: "+ str(spinbox.get())
    label.config(text=var)

window = tk.Tk()

spinbox = tk.Spinbox(window, from_= 0, to=10, increment=1, font=('Helvetica',14), foreground='blue', command=selection)
spinbox.pack(pady=10)

label = tk.Label(window, text="Please select a value", font=('Helvetica',14))
label.pack(pady=10)

window.mainloop()

In this example, we create a Spinbox widget with a range of 0-10 with an increment of 1, and a font size of 14 in the Helvetica font. The selection function is called when the value in the Spinbox changes. The output label displays the selected value.

Output

Spinbox Output

Explanation

In the example code above, we create a Spinbox widget by defining its range, increment value, font, foreground color, and command function. Then, we create a label widget to display the selected value from the Spinbox. The selection() function takes the value from the Spinbox and shows it on the output label.

Use

Spinbox is useful for accepting numerical input in limited and predefined ranges. It is beneficial for user interfaces and GUI based applications in setting limits and managing numerical input.

Important Points

  • Spinbox provides an intuitive way for users to input numerical values.
  • Always define the from_ and to attributes to limit the range of values, as well as the increment attribute.
  • The command attribute is used to define the function that acts whenever the value changes.
  • The font and foreground attributes can be used to customize the display of the Spinbox.

Summary

The Spinbox widget is a user interface element in Tkinter that allows users to input numerical values in a limited or predetermined range. It's efficient for managing numerical input and setting limits on ranges. With the help of the command attribute, the Spinbox can be linked with other components to perform various actions when the user makes a selection.

Published on: