Sunday, November 17, 2024
Google search engine
HomeLanguagesPython Tkinter – Validating Entry Widget

Python Tkinter – Validating Entry Widget

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.

  1. Import tkinter module
    import tkinter
  2. Import tkinter submodules
    from tkinter import *
  3. Define the “callback” function
    def callback(input):
        if input.isdigit():
            print(input)
            return True
                            
        elif input is "":
            print(input)
            return True
    
        else:
            print(input)
            return False

    Explanation
    The 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.

  4. Creating the parent window
    root=Tk()

    Syntax: Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)
    Parameter: In this example, Tk class is instantiated without arguments.
    Explanation
    This method creates a parent widget which usually is the main window of an application.

  5. Creating Entry widget
    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) .
    Explanation
    This method is used to create the Entry widget on the parent widget (root) .

  6. Specify the position of Entry widget within the parent window
    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) .

  7. Register the callback function
    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.
    Explanation
    The register() method returns a string which is assigned to a variable ‘reg’ that is used to call the callback function in the later stages.

  8. Call the callback function to validate the input in Entry widget
    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.

    Explanation
    Validate 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 function
    The 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.

  9. Run the application
    root.mainloop()

    Syntax: mainloop()
    Explanation
    The 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 tkinter
from 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)

Explanation
When 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.

RELATED ARTICLES

Most Popular

Recent Comments