Python tkinter Spinbox



Tkinter Spinbox

Tkinter Spinbox to select value from given list or range and how to set and get value with options


Using Spinbox user can select value from a range of given options.
Two SpinBox widgets, one for integer and other one is for string selection by user.
import tkinter as tk
from tkinter import *
my_w = tk.Tk()
my_w.geometry("300x150")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title

sb1 = Spinbox(my_w, from_= 0, to = 10,width=5)
sb1.grid(row=1,column=1,padx=20,pady=20)

my_list=['One', 'Two', 'Three', 'Four', 'Five']
sb2 = Spinbox(my_w,values=my_list,width=10)
sb2.grid(row=1,column=2,padx=20,pady=20)

my_w.mainloop()  # Keep the window open
User can use the arrow buttons to change the options or enter directly the value.

How to set default value for Spinbox 🔝

Default value set for Tkinter Spinbox
By using StringVar we can set the default value of the Spinbox. Here for both the types ( number and string ) of Spinbox widgets, two different string variables ( t1 and t2 ) are used and by using set() method the default values are set.

We must set the value t2.set('Four') after creating the widget.
t1 = StringVar() # string variable 
sb1 = Spinbox(my_w, from_= 0, to = 10,width=5,textvariable=t1)
sb1.grid(row=1,column=1,padx=20,pady=20)
t1.set(5) # set value for string variable 

t2=StringVar() # string variable
my_list=['One', 'Two', 'Three', 'Four', 'Five']
sb2 = Spinbox(my_w,values=my_list,width=10,textvariable=t2)
sb2.grid(row=1,column=2,padx=20,pady=20)
t2.set('Four')#set value for string vaiable

Reading the value of Spinbox with on change of selection 🔝

Reading value on change event of  Tkinter Spinbox
We used two Labels here. The first Label ( l1 ) is connected to the Spinbox ( sb2 ) through StringVar t2. So once the selection of Spinbox is changed the value of StringVar t2 is reflected in Label ( l1).

The second Label ( l2 ) gets its value by this line l2.config(text=sb2.get()) inside the function desp(). This function desp() is triggered through the command attribute of Spinbox ( command=desp )
import tkinter as tk
from tkinter import *
my_w = tk.Tk()
my_w.geometry("300x150") 

def desp():
    l2.config(text=sb2.get()) # 2nd Label value
    print(sb2.get()) # output at console 
    print(t2.get())  # output at console
	
font1=('Times',24,'bold')	
t2 = StringVar() # connected to 1st Label and Spinbox
my_tuple=['One', 'Two', 'Three', 'Four', 'Five']
sb2 = Spinbox(my_w,values=my_tuple,font=font1,width=5,
    textvariable=t2, command=desp)
sb2.grid(row=1,column=2,padx=18,pady=30)

l1 = tk.Label(my_w,  textvariable=t2, width=10,bg='yellow' )
l1.grid(row=1,column=3) 

l2 = tk.Label(my_w,  width=10 ,text='data here',bg='lightblue')
l2.grid(row=1,column=4,padx=2) 
my_w.mainloop()  # Keep the window open

Enable disable Spinbox 🔝

To disable we can use option state or use config().
sb1 = Spinbox(my_w, from_= 0, to = 10, state='disabled')
or using config()
sb1.config(state='disabled')
We can restore by using state='normal'
sb1.config(state='normal')
The third value of state is readonly. We can't use insert() method when state='readonly'
sb1.config(state='readonly')

Methods 🔝

delete(first, last=None): Delete one ore more char from the element.
get: Returns the Spinbox string ( Check above examples)
insert(index,string): Place the string at Index position.
index(index): Returns numerical Index.
identify(x,y):Returns the name of the widget at position x, y
invoke:Causes the specified element to be invoked

Using delete and insert methods 🔝

We will remove four and place FOUR as element.
t2 = StringVar()
my_list=['One', 'Two', 'Three', 'Four', 'Five']
sb2 = Spinbox(my_w,values=my_list,  textvariable=t2, width=10)
sb2.grid(row=1,column=2,padx=20)
t2.set('Four')
sb2.delete(0,'end') # replace from 0 position till end
sb2.insert(0,'FOUR') # add string from 0 position
Above codes will not update any option when state='readonly' or state='disabled'

Creating Interlinked Spinboxes in Tkinter for Range Selection 🔝

Interlinked two spinboxes
We will create two interlinked Tkinter Spinbox widgets that allow the user to select a range of values, we'll set up the first Spinbox to control the minimum value and the second to control the maximum value of the range.

The key here is to ensure that the value in the first Spinbox (min value) is always less than or equal to the value in the second Spinbox (max value). Similarly the value in second Spinbox is alway greate than or equal to value in first Spinbox.
Two interlinked spinboxes for dynamic range selection with Lower and upper limits to generate query
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("620x350")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title

font1=('Times',84,'bold') # Higher font for Spinbox 
font2=('Times',34,'normal') # Higher font for Label text 

def my_upd():
    sb2.config(from_=sb1.get()) # set lower limit for second Spinbox
    sb1.config(to=sb2.get())    # set upper limit for first Spinbox 
    lb1.config(text='BETWEEEN ' + sb1.get() + ' AND ' + sb2.get()) # Label text

v1=tk.IntVar(value=10) #  for first Spinbox 
sb1 = tk.Spinbox(my_w, from_= 0, to = 100,width=3,textvariable=v1,
                 font=font1,bg='lightgreen',command=my_upd)
sb1.grid(row=1,column=1,padx=30,pady=35)

v2=tk.IntVar(value=20) # for second Spinbox 
sb2 = tk.Spinbox(my_w, from_= 0, to = 100,width=3,textvariable=v2,
                 font=font1,bg='lightpink',command=my_upd)
sb2.grid(row=1,column=2,padx=30,pady=20)

lb1=tk.Label(my_w,text='Query here',font=font2, bg='lightblue',width=20)
lb1.grid(row=2,column=1,columnspan=2,padx=30, pady=20)

my_w.mainloop()  # Keep the window open

Adding new options / values 🔝

When we used from_ and to to add a range, we can change these values by using config()
sb1.config(from_=40,to=50) # starting from 40 to 50
When we are using values option we can change by using list insert()
my_list=['One','Two','Three','Four','Five']
sb2=tk.Spinbox(my_w,values=my_list,width=10,textvariable=t2)
sb2.grid(row=1,column=2)
my_list.insert(5,'Six') # added option six at index position 5
sb2.config(values=my_list)

Inter connecting Spinbox and Scale widgets 🔝

We can add one horizontal scrollbar by using one Scale widget. Here both are connected so changes in any one will reflect in both.
We used one common StringVar sv here.
Connected Scale and Spinbox
import tkinter as tk
from tkinter import *
my_w = tk.Tk()
my_w.geometry("300x200") 
my_w.title("www.plus2net.com") 

font1=('Arial',24,'bold')
sv = StringVar() #string variable 
sb = Spinbox(my_w,textvariable=sv,font=font1,
     width=3,from_=0,to=100)
sb.grid(row=1,column=1,padx=30,pady=10)

sc = Scale(my_w, from_=0, to=100, font=font1,
    orient=HORIZONTAL,variable=sv,length=180)
sc.grid(row=2,column=1,padx=30)

my_w.mainloop()  # Keep the window open

Options 🔝

activebackgroundColor of the slider when Mouse is over it.
bgColor of the slider and arrowheads when Mouse is NOT over it.
bdBorder width of the widget
commandWhen state is changed call the function. ( Example above )
bdBorder width of the widget
cursorShape of the cursor while moving over the Spinbox ( List of cursor shapes )
disabledbackgroundBackground color when it is disabled
sb1 = Spinbox(my_w, from_= 0, to = 10,
disabledbackground='yellow',state='disabled')
disabledforegroundForeground color when it is disabled
sb1 = Spinbox(my_w, from_= 0, to = 10,
disabledforeground='blue',state='disabled')
fontFont family size style
my_font=('Times',18,'normal')
sb1 = Spinbox(my_w, from_= 0, to = 10,
font=my_font)
fgForeground colour
sb1 = Spinbox(my_w, from_= 0, to = 10,fg='blue')
formatFormat the display, showing decimal place or starting with zero etc.
sb1 = Spinbox(my_w, from_= 00, to = 60,format='%02.02f')
from_Start value of Spinbox, check examples above.
incrementStep value of change when we use the arrow buttons.
justifyAlignment of text inside. ( left , center, right )
sb1 = Spinbox(my_w, from_= 0, to = 60,justify='right')
reliefBorder style, ( raised, sunken,flat,ridge,solid,groove ) Check the Button for sample images
sb1 = Spinbox(my_w, from_= 0, to = 60,relief='solid')
statestate of Spinbox , ( disabled, normal, readonly) Check the examples above
sb1 = Spinbox(my_w, from_= 0, to = 60,state='disabled')
validateWhen to Validate the input ( none,focus,focusin,focusout,key,all)
sb1 = Spinbox(my_w, from_= 0, to = 60,validate='key')
validatecommandCallback function to execute validation
sb1 = Spinbox(my_w, from_= 0, to = 10,
validate='key',validatecommand=(my_valid,'%s'))
More on input Validation
toEnd value of Spinbox, check examples above.
repeatdelayDelay in changing value when you press the Up or down arrow and holding it ( for first time ) in milliseconds
sb1 = Spinbox(my_w,from_=0,to=100,repeatdelay=4000)
What is the difference between repeatdelay and repeatinterval ?
repeatintervalDelay in changing value in each step when you press the Up or down arrow and holding it in milliseconds
sb1 = Spinbox(my_w,from_=0,to =100,repeatinterval=3000)
Why in this code the first change is not matching with repeatinterval of 3 sec ? Try to add repeatdelay and see the difference
xscrollcommandUsed with set method of scrollbar
wrapBoolean, default value is False. If it is set to True then value starts ( repeat ) from lower limit ( from_) after the maximum value ( to ) is reached.
sb1 = Spinbox(my_w, from_= 0, to = 10,wrap=True)
widthControl the width of the spinbox ( examples above)
vcmdSee validatecommand above
valuesThe options we can add, see examples above (sb2)
textvariableThe variable to connect to the widget, check the examples above where we used t2 the StrVariable to sb2


Displaying incremental data based on timer with step value & upper limit in Entry widget of Tkinter


Projects using Spinbox 🔝

  1. Display two Spinboxes showing numbers and on click of a button display the sum of the selected numbers.
  2. Collect all student names from MySQL table and display them using Spinbox. On submit of a button display full details of the selected record ( student ).

Questions 🔝


MySQL , SQLite,CSV and Json data is used to add options for Spinbox
Dynamically managing Spinboxes
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer