Python Tkinter – SpinBox range Validation
Prerequisites: Python GUI – tkinter, Python Tkinter – Validating Entry Widget
Tkinter is a Python GUI (Graphical User Interface) module which is quick and easy to implement and is widely used for creating desktop applications. It provides various basic widgets to build a GUI program. In Tkinter, Spinbox is commonly used widget to select the fixed number of values from the range provided by the programmer, but by default Spinbox accepts all types of input given by user. Hence we need to validate the input and accept only those values which are in the range.
Below is the implementation:
Note: For more information on Validatecommand, refer to Python Tkinter – Validating Entry Widget
Python3
from tkinter import *
def validate(user_input):
if user_input.isdigit():
minval = int (root.nametowidget(spinbox).config( 'from' )[ 4 ])
maxval = int (root.nametowidget(spinbox).config( 'to' )[ 4 ])
if int (user_input) not in range (minval, maxval):
print ( "Out of range" )
return False
print (user_input)
return True
elif user_input is "":
print (user_input)
return True
else :
print ( "Not numeric" )
return False
root = Tk()
root.geometry( "300x300" )
root.title( "Spinbox Range Validation" )
spinbox = Spinbox(root, from_ = 1 , to = 1000 )
spinbox.pack()
range_validation = root.register(validate)
spinbox.config(validate = "key" ,
validatecommand = (range_validation, '% P' ))
root.mainloop()
|
Output:
Last Updated :
17 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...