Python Tkinter – Validating Entry Widget

26 Mar, 2020
Python offers a variety of frameworks to work with GUI applications. Tkinter or Tk interface is one of the most widely used Python interface to build GUI based applications. There are applications that require validation of text fields to prevent invalid input from the user before the form is submitted. Python allows input validation by allowing variable tracing using a callback function. This function is called whenever an input is added/deleted to/from an Entry widget. Some applications validate input on form submission, but the following piece of code performs validation with every stroke of key from the keyboard.
Import tkinter moduleimport tkinterImport tkinter submodulesfrom tkinter import *Define the “callback” functiondef callback(input):
    if input.isdigit():
        print(input)
        return True
                        
    elif input is "":
        print(input)
        return True

    else:
        print(input)
        return FalseExplanationThe callback function checks the input in the Entry widget for valid entry. If the entry is valid it returns True else False. In this example, the input entered through the keyboard is checked for numeric type. If the input is numeric type then the callback function returns true. For deletion operation the callback function returns true as input is “” . However for any non-numeric input the callback function returns false.Creating the parent windowroot=Tk()Syntax: Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)Parameter: In this example, Tk class is instantiated without arguments.ExplanationThis method creates a parent widget which usually is the main window of an application.Creating Entry widgete=Entry(root)Syntax: Entry(master, **options)Parameter:master: Represents the parent window (here root) .options: The supported options are bg, bd, command, cursor, font, exportselection, justify, relief, highlightcolor, fg, selectbackground, selectforeground, selectborderwidth, show, xscrollcommand, state, textvariable and width.Return Value: Returns a string (.!entry) .ExplanationThis method is used to create the Entry widget on the parent widget (root) .Specify the position of Entry widget within the parent windowe.place(x=50, y=50)Syntax: place(x, y)Parameter:x: Position of the Entry widget with respect to parent widget along X axis.y: Position of the Entry widget with respect to parent widget along Y axis.Explanation:This method specifies the position of Entry widget in the parent window (root) .Register the callback functionreg=root.register(callback)Syntax: register(function)Parameter:function: The function that is to be called to validate the input in the Entry widget.Return Value: This method returns a character string that can be used to call the function.ExplanationThe register() method returns a string which is assigned to a variable ‘reg’ that is used to call the callback function in the later stages.Call the callback function to validate the input in Entry widgete.config(validate="key", validatecommand=(reg, '%P'))Syntax: config(validate=”key”, validatecommand=(reg, ‘%P’))Parameter:validate: This option is used to specify when the callback function will be called to validate the input. The “key” value specifies that validation occurs whenever any keystroke(input from keyboard) changes the widget’s contents.validatecommand: This option is used to specify the callback function. The function is not called directly rather a variable is passed which was registered in the earlier steps. ‘%P’ is passed to denote the value that the text will have if the change is allowed.ExplanationValidate option supports other values such as focus, focusin, focusout, all and none. The default value is “none”, which means that there is no validation.Validatecommand option supports other values such as %d, %i, %s, %S, %v, %V and %W . The percent substitution can be added for each parameter to be passed to the Python functionThe Entry widget also supports an invalidcommand option that calls a function whenever the validatecommand returns False.These can be used based on the requirement of the user.Run the applicationroot.mainloop()Syntax: mainloop()ExplanationThe mainloop() is an infinite loop used to run the application as long as the window is not closed.
Import tkinter moduleimport tkinter
import tkinter
Import tkinter submodulesfrom tkinter import *
from tkinter import *
Define the “callback” functiondef callback(input):
    if input.isdigit():
        print(input)
        return True
                        
    elif input is "":
        print(input)
        return True

    else:
        print(input)
        return FalseExplanationThe callback function checks the input in the Entry widget for valid entry. If the entry is valid it returns True else False. In this example, the input entered through the keyboard is checked for numeric type. If the input is numeric type then the callback function returns true. For deletion operation the callback function returns true as input is “” . However for any non-numeric input the callback function returns false.
def callback(input):
    if input.isdigit():
        print(input)
        return True
                        
    elif input is "":
        print(input)
        return True

    else:
        print(input)
        return False
ExplanationThe callback function checks the input in the Entry widget for valid entry. If the entry is valid it returns True else False. In this example, the input entered through the keyboard is checked for numeric type. If the input is numeric type then the callback function returns true. For deletion operation the callback function returns true as input is “” . However for any non-numeric input the callback function returns false.
Creating the parent windowroot=Tk()Syntax: Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)Parameter: In this example, Tk class is instantiated without arguments.ExplanationThis method creates a parent widget which usually is the main window of an application.
root=Tk()
Syntax: Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)Parameter: In this example, Tk class is instantiated without arguments.ExplanationThis method creates a parent widget which usually is the main window of an application.
Creating Entry widgete=Entry(root)Syntax: Entry(master, **options)Parameter:master: Represents the parent window (here root) .options: The supported options are bg, bd, command, cursor, font, exportselection, justify, relief, highlightcolor, fg, selectbackground, selectforeground, selectborderwidth, show, xscrollcommand, state, textvariable and width.Return Value: Returns a string (.!entry) .ExplanationThis method is used to create the Entry widget on the parent widget (root) .
e=Entry(root)
Syntax: Entry(master, **options)Parameter:
master: Represents the parent window (here root) .
options: The supported options are bg, bd, command, cursor, font, exportselection, justify, relief, highlightcolor, fg, selectbackground, selectforeground, selectborderwidth, show, xscrollcommand, state, textvariable and width.
Return Value: Returns a string (.!entry) .ExplanationThis method is used to create the Entry widget on the parent widget (root) .
Specify the position of Entry widget within the parent windowe.place(x=50, y=50)Syntax: place(x, y)Parameter:x: Position of the Entry widget with respect to parent widget along X axis.y: Position of the Entry widget with respect to parent widget along Y axis.Explanation:This method specifies the position of Entry widget in the parent window (root) .
e.place(x=50, y=50)
Syntax: place(x, y)Parameter:
x: Position of the Entry widget with respect to parent widget along X axis.
y: Position of the Entry widget with respect to parent widget along Y axis.
Explanation:This method specifies the position of Entry widget in the parent window (root) .
Register the callback functionreg=root.register(callback)Syntax: register(function)Parameter:function: The function that is to be called to validate the input in the Entry widget.Return Value: This method returns a character string that can be used to call the function.ExplanationThe register() method returns a string which is assigned to a variable ‘reg’ that is used to call the callback function in the later stages.
reg=root.register(callback)
Syntax: register(function)Parameter:
function: The function that is to be called to validate the input in the Entry widget.
Return Value: This method returns a character string that can be used to call the function.ExplanationThe register() method returns a string which is assigned to a variable ‘reg’ that is used to call the callback function in the later stages.
Call the callback function to validate the input in Entry widgete.config(validate="key", validatecommand=(reg, '%P'))Syntax: config(validate=”key”, validatecommand=(reg, ‘%P’))Parameter:validate: This option is used to specify when the callback function will be called to validate the input. The “key” value specifies that validation occurs whenever any keystroke(input from keyboard) changes the widget’s contents.validatecommand: This option is used to specify the callback function. The function is not called directly rather a variable is passed which was registered in the earlier steps. ‘%P’ is passed to denote the value that the text will have if the change is allowed.ExplanationValidate option supports other values such as focus, focusin, focusout, all and none. The default value is “none”, which means that there is no validation.Validatecommand option supports other values such as %d, %i, %s, %S, %v, %V and %W . The percent substitution can be added for each parameter to be passed to the Python functionThe Entry widget also supports an invalidcommand option that calls a function whenever the validatecommand returns False.These can be used based on the requirement of the user.
e.config(validate="key", validatecommand=(reg, '%P'))
Syntax: config(validate=”key”, validatecommand=(reg, ‘%P’))Parameter:
validate: This option is used to specify when the callback function will be called to validate the input. The “key” value specifies that validation occurs whenever any keystroke(input from keyboard) changes the widget’s contents.
validatecommand: This option is used to specify the callback function. The function is not called directly rather a variable is passed which was registered in the earlier steps. ‘%P’ is passed to denote the value that the text will have if the change is allowed.
ExplanationValidate option supports other values such as focus, focusin, focusout, all and none. The default value is “none”, which means that there is no validation.Validatecommand option supports other values such as %d, %i, %s, %S, %v, %V and %W . The percent substitution can be added for each parameter to be passed to the Python functionThe Entry widget also supports an invalidcommand option that calls a function whenever the validatecommand returns False.These can be used based on the requirement of the user.
Run the applicationroot.mainloop()Syntax: mainloop()ExplanationThe mainloop() is an infinite loop used to run the application as long as the window is not closed.
root.mainloop()
Syntax: mainloop()ExplanationThe mainloop() is an infinite loop used to run the application as long as the window is not closed.
Complete code for validation of Entry widget
import tkinterfrom tkinter import *    def callback(input):          if input.isdigit():        print(input)        return True                              elif input is "":        print(input)        return True      else:        print(input)        return False                          root = Tk()  e = Entry(root)e.place(x = 50, y = 50)reg = root.register(callback)  e.config(validate ="key",          validatecommand =(reg, '% P'))  root.mainloop()
Output: (Full Screen View Recommended)
ExplanationWhen we enter digits using our keyboard the callback function returns true and the value is allowed in the entry widget. However on entering alphabets from the keyboard the callback function returns false and the value is not allowed to entered in the entry widget. To get a clearer idea about the working of the callback function the input sent through the keyboard is printed on the console. It can be seen that any non-numeric input gets printed on the console but is not allowed in the entry widget. Also both insertion and deletion of numerics are allowed in the entry widget.
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Read JSON file using Python
Python map() function
How to iterate through Excel rows in Python?
Enumerate() in Python
Adding new column to existing DataFrame in Pandas
Python OOPs Concepts
Different ways to create Pandas Dataframe
How to get column names in Pandas dataframe
Stack in Python