Python Tkinter – SpinBox range Validation

Prerequisites: Python GUI – tkinter, Python Tkinter – Validating Entry Widget 

Tkinter is a Python GUI (Graphical User Iterface) 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 provied 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

filter_none

edit
close

play_arrow

link
brightness_4
code

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
        print(user_input)
        return True
  
    # if input is blank string
    elif user_input is "":
        print(user_input)
        return True
  
    # return false is input is not numeric
    else:
        print("Not numeric")
        return False
  
  
root = Tk()
root.geometry("300x300")
root.title("Spinbox Range Validation")
  
# Creating Spinbox
spinbox = Spinbox(root, from_ = 1, to = 1000)
spinbox.pack()
range_validation = root.register(validate)
  
spinbox.config(validate ="key",
         validatecommand =(range_validation, '% P'))
  
root.mainloop()

chevron_right


Output: 
 



 

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.