Python tkinter Spinbox

A Spinbox widget allows the user to select values from a given set of values.The values may be a range of numbers or a fixed set of strings.The spin box appears as a long rectangle attached with arrowheads pointing towards up and down.The user can click on the arrowheads to see the next value or previous value. The user can also edit the value being displayed in the spin box just like he can do in case of an Entry widget. A spin box is created as an object of Spinbox class.

tkinter Spinbox

To create a spin box with numbers ranging from 5 to 15, we can write the following statement:


CopiedCopy Code
s1 = Spinbox(f, from_= 5, to=15, textvariable=val1, width=15, fg='blue', bg='yellow', font=('Arial', 14, 'bold'))

Here, 'f' represents the parent widget. 'from_' indicates the starting value and 'to' indicates the ending value in the spin box.'textvariable' shows the control variable, i.e. val1 that is created as an object of the IntVar class, as follows:

CopiedCopy Code
val1 = IntVar()

'val1' is a control variable that receives the displayed value in the spin box.Similarly, we can create a spin box with strings by specifying the strings as a tuple as shown in the following statement:

CopiedCopy Code
s2 = Spinbox(f, values=('Hyderabad', 'Delhi', 'Kolkata', 'Bangalore'), textvariable=val2, width=15, fg='black', bg='green', font=('Arial', 14, 'bold italic'))

Here, the fixed strings that are displayed in the spin box are mentioned in the 'values' option as a tuple as shown in the following statement:

CopiedCopy Code
values=('Hyderabad', 'Delhi', 'Kolkata', 'Bangalore')

The 'textvariable' option indicates the control variable value 'val2' that is created as an object of StringVar class as shown in the following statement:

CopiedCopy Code
val2 = StringVar()

'val2' contains the displayed string in the spin box. To retrieve the values from the control variables, we can use the get() method as:

CopiedCopy Code
a = val1.get()# get the number from val1
s = val2.get()# get the string from val2

tkinter Spinbox example

A Python program to create two spin boxes and retrieve the values displayed in the spin boxes when the user clicks on a push button.

CopiedCopy Code

from tkinter import * 
class MySpinbox: 
   def __init__(self, root):
      self.f = Frame(root, height=350, width=500) 
      self.val1 = IntVar() 
      self.val2 = StringVar() 
      #create Spinbox with numbers from 5 to 15 
      self.s1 = Spinbox(self.f, from_= 5, to=15, textvariable=self.val1,width=15, fg='blue', bg='yellow', font=('Arial', 14, 'bold')) 
#create Spinbox with a tuple of strings 
      self.s2 = Spinbox(self.f, values=('Hyderabad', 'Delhi', 'Kolkata','Bangalore'), textvariable=self.val2, width=15, fg='black',bg='LightGreen', font=('Arial', 14, 'bold italic')) 
      self.b = Button(self.f, text='Get values from spinboxes', command=self.display), y=50), y=100), y=150) 
   def display(self): 
      a = self.val1.get()
      s = self.val2.get()