Validating Entry Widget in Python Tkinter

The Python programming language provides a range of frameworks to work with Graphical User Interface (GUI) applications. The Tkinter or Tk interface is among Python's most commonly utilized interfaces to construct applications based on Graphical User Interface (GUI). Some applications require validation of the text fields to prevent invalid input from the user before the form is submitted. Python enables the validation of the input by allowing the tracing of the variable with the help of a callback function. This function is called when input is added to/deleted from an Entry widget of the Tkinter package.

In the following tutorial, we will learn how to validate the user inputs using the Tkinter package.

So, let's get started.

An Introduction to the Tkinter Validation

Validation in Python Tkinter means declaring the user inputs officially acceptable. In other words, validation is referred to as checking whether the information shared by the user meets the requirements.

There are primarily three types of Validations:

  • Type Check:This validation is performed to check the data type of the input.
  • Length Check:This validation is performed to check the minimum or maximum length of the input.
  • Range Check:This validation is performed to check the range of the input.

The Validation in Python Tkinter depends upon three arguments or parameters that we can utilize for any input widget like the Entry() widget:

  1. validate: This argument is used to denote which type of event will trigger the validation.
  2. validatecommand: This argument is used to check whether the data is valid.
  3. invalidcommand: This argument is executed when the data is invalid. In order words, it will execute if the return value of the validatecommand argument is False.

Let us now briefly understand some basic concepts of these arguments or commands.

The validate argument

The validate argument can be one of the string values as follows:

S. No.String Value(s)Description(s)
1'focus'This string value validates when the widget gets or loses the focus.
2'focusin'This string value validates when the widget gets focus.
3'focusout'This string value validates when the widget loses focus.
4'key'This string value validates when any keystroke alters the content of the widget.
5'all'This string value validates in all the situations mentioned above, like 'focusin', 'focusout', and 'key'.
6'none'This string value turns off the validation. This is the default.
Note: The string 'none' is not the same as the None value in Python.

The validatecommand argument

The validatecommand argument is a tuple consisting of:

  1. A reference/address to a Tcl/Tk function.
  2. Zero or more substitution codes state the information triggering the event we would like to pass into the function.

We will pass a callable to the widget_name.register() method in order to get a reference to a Tcl/Tk function. This method will return a string we can utilize with the validatecommand option.

Let us consider the following table that displays the substitution codes which we can utilize with the tuple:

S. No.Substitution Code(s)Description(s)
1%dAction code: 0 for a tried deletion, 1 for a tried insertion, or -1 if the callback function was called for focus in, focus out, or an alteration to the text variable.
2%iWhenever the user tries to delete or insert text, this parameter will be the index of the starting of the insertion or deletion. If the callback function were due to focus in, focus out, or an alteration to the parameter, the argument would be -1.
3%PThe value that the text will have in case the change is permitted.
4%sThe text in the entry before the change.
5%SIn case the call was due to deletion or insertion, this argument will be the text being deleted or inserted.
6%vThe present value of the validate option of the widget.
7%VThis callback is due to one of the string values, i.e., 'focusin', 'focusout', 'key', or 'forced', if the text variable is altered.
8%WThe name of the widget.

Let us consider the following example to construct a validatecommand option using the self.validate() method and %P substitution code:

Example:

The invalidcommand argument

Similar to validatecommand argument, the invalidcommand argument also requires the utilization of the widget_name.register() method and the substitution code.

Let us consider the following example that returns a tuple by passing into the invalidcommand option:

Example:

An Example based on Tkinter Validation

In this example, we will create a form consisting of an e-mail input. If the entered e-mail address is invalid, it will display an error message and change the color of the e-mail input. Moreover, we will trigger the validation event when the focus moves out of the entry.

Let us consider the following snippet of code to understand the implementation of the above statement.

Program Code:

Output 1: If the entered e-mail address is valid.

Validating Entry Widget in Python Tkinter

Output 2: If the entered e-mail address is not valid.

Validating Entry Widget in Python Tkinter

How does validation work in the above example?

Firstly, we have created a validate command with the help of the self.validate() method and %P substitution code.

Syntax:

Secondly, we have created the invalidcommand command that utilizes the self.on_invalid() method.

Syntax:

Next, we have configured the entry widget that utilizes the validate, validatecommand, and invalidcommand parameters.

Syntax:

Moreover, we have defined the displayMessage() method that alters the text of the error_label widget and the text color of the email_field widget.

Syntax:

After that, we have defined another method as validate() that performs validation of the value of the email_field widget.

Syntax:

The validate() method in the above snippet of code returns True if the input text is valid; otherwise, it returns False. If the entered text is a valid e-mail address, call the displayMessage() method to hide the error message and set the color of the text to black.

If the entered text turns out to be an invalid e-mail address, Tkinter will run the on_invalid() method.

At last, we have defined the on_invalid() method to display an error message and set the color of the text of the email_field widget to red.

Syntax:

The Conclusion

  1. The Tkinter package utilizes the validate, validatecommand, and invalidcommand parameters on any input widget in order to validate the input data.
  2. We have to pass a callable to the register() method in order to create a command for validatecommand and invalidacommand parameters.
  3. The validatecommand parameter returns True for the valid data, whereas it returns False for the invalid one.
  4. The invalidcommand parameter will be executed if the data is invalid or when the validatecommand parameter returns False.





Latest Courses