Skip to content
Related Articles

Related Articles

Python Tkinter – SpinBox range Validation

Improve Article
Save Article
Like Article
  • Last Updated : 17 Sep, 2021

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 


from tkinter import *
# Validating function
def validate(user_input):
    # check if the input is numeric
    if  user_input.isdigit():
        # Fetching minimum and maximum value of the spinbox
        minval = int(root.nametowidget(spinbox).config('from')[4])
        maxval = int(root.nametowidget(spinbox).config('to')[4])
        # check if the number is within the range
        if int(user_input) not in range(minval, maxval):
            print ("Out of range")
            return False
        # Printing the user input to the console
        return True
    # if input is blank string
    elif user_input is "":
        return True
    # return false is input is not numeric
        print("Not numeric")
        return False
root = Tk()
root.title("Spinbox Range Validation")
# Creating Spinbox
spinbox = Spinbox(root, from_ = 1, to = 1000)
range_validation = root.register(validate)
spinbox.config(validate ="key",
         validatecommand =(range_validation, '% P'))



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!