Validating Entry Widget In Python Tkinter

When developing graphical user interfaces (GUIs) in Python, Tkinter is a powerful and widely-used toolkit that simplifies the process. One of the common tasks in GUI applications is obtaining user input through form fields. Tkinter’s Entry widget is designed for this purpose, allowing users to input text. However, ensuring the correctness of the entered data is crucial. This article will discuss how to validate input in the Entry widget using Tkinter, providing practical examples to illustrate the concept.

Entry Widget in Python Tkinter

The Entry widget in Python Tkinter is a standard single-line text entry field that allows users to input text. It is commonly used in forms where the user is required to enter information such as names, passwords, or other textual data. The Entry widget can be customized and controlled in various ways, including validating the input to ensure that the data entered meets specific criteria before being processed further.

Steps to Validate Entry Widget in Tkinter

There are a number of ways to validate an Entry widget. Here we will create a Tkinter window which will have a label, an entry widget, and a button. When the user enters some data in the Entry widget and clicks the Button, a function is called to validate the data entered by the user. It will then display a message popup window displaying whether the data is valid or invalid.

Let us see the steps to create such a validity check on the Entry widget.

Import Modules

The first step is to import the modules, that is the Tkinter and messagebox widget. The Tkinter module is used to create the main window application and other widgets whereas the messagebox widget is used for a popup window that displays a message.

import tkinter as tk
from tkinter import messagebox

Create Tkinter Window

Next, create the main application window using tk.Tk() class. It is the parent or root window that contains all other Tkinter widgets such as buttons, labels, entries, etc. We can also provide a title and dimensions for the Tkinter window.

root = tk.Tk()
root.title("title_to_display")
root.geometry("300x200")

Create Required Widgets

Add the necessary widgets that you want to display on the Tkinter window. Here we require three widgets – Label, Entry, and Button.

label = tk.Label(root, text="text_to_display")
entry = tk.Entry(root)
btn = tk.Button(root, text="text_to_display")
label.pack()
entry.pack()
btn.pack()

Define Validation Function

Create a function to validate the input based on specific criteria, such as checking for only digits, and alphabets and making sure the entry widget is not empty.

data.isdigit()
data.isalpha()

Bind Validation to Submit Button

Validate the input when the user presses the submit button. The Button() function’s third parameter, that is command will have the value of a function name that is to be called when the button is clicked. This function will check for validity.

btn = tk.Button(root, text="text_to_display", command=function_to_call)

Run the Main Event Loop

Finally, run the main event loop to display the window and make the application responsive to user interactions.

root.mainloop()

Examples to Validate Entry Widget in Tkinter

Here are a few different examples demonstrating how to validate an Entry widget in Tkinter.

Numeric Validation: Validating Phone Number

In this example, we will create a Tkinter window that will validate that the input is a numeric value. We will ask the user to enter a phone number, that is, the entered data is only digits and is of 10 characters. This will be done by using Python string isdigit() and len() functions. When the user enters the data and hits the submit button, the result will be displayed in a message box.

Python
# import modules
import tkinter as tk
from tkinter import messagebox

# function to check valid phone number
def validate_phone(phone):
    if phone.isdigit() and len(phone) == 10:
        return True
    return False

# function called when Submit is ckicked
def on_submit():
    phone = phone_entry.get()
    if not validate_phone(phone):
        messagebox.showerror("Invalid Input",
                             "Phone number must be exactly 10 digits.")
    else:
        messagebox.showinfo("Valid Input",
                            "Phone number is valid.")

# main Tkinter application window
root = tk.Tk()
root.title("Phone Number Validation")
root.geometry("300x200")

# tkinter widgets
phone_label = tk.Label(root, text="Phone Number:")
phone_label.pack()
phone_entry = tk.Entry(root)
phone_entry.pack()

# sumit buttion to check validity
submit_button = tk.Button(root, text="Submit", command=on_submit)
submit_button.pack()

root.mainloop()

Output:

Validating Entry Widget on Numeric Data

Validating Entry Widget on Numeric Data

String Validation: Validating Name

In this example, we will create a Tkinter window that will validate that the input is a string value. We will ask the user to enter a name, that is, the entered data is only alphabet characters (A-Z or a-z). This will be done by using Python string isalpha() function. When the user enters the data and hits the submit button, the result will be displayed in a message box.

Note: It will check for only the First/Last name, that is, there should be only one word without any white space.

Python
# import modules
import tkinter as tk
from tkinter import messagebox

# function to check valid name (string)
def validate_name(name):
    if name.isalpha():
        return True
    return False

# function called when Submit is ckicked
def on_submit():
    name = name_entry.get()
    if not validate_name(name):
        messagebox.showerror("Invalid Input", 
                             "Name must contain only alphabets.")
    else:
        messagebox.showinfo("Valid Input",
                            "Name is valid.")

# main Tkinter application window
root = tk.Tk()
root.title("Name Validation")
root.geometry("300x200")

# tkinter widgets
name_label = tk.Label(root, text="Name:")
name_label.pack()
name_entry = tk.Entry(root)
name_entry.pack()

# sumit buttion to check validity
submit_button = tk.Button(root, text="Submit", command=on_submit)
submit_button.pack()

root.mainloop()

Output:

Validating Entry Widget on String Data

Validating Entry Widget on String Data

Special Validation: Validating Email

In this example, we will create a Tkinter window that will validate that the input is a special value. This means it can contain alphanumeric values as well as a few special characters. This will be done by using another Python module known as Regular Expression, aka RegEx module. This module is best used for pattern matching and here using its match() function we can check for a valid email.

We will ask the user to enter the email address. When the user enters the data and hits the submit button, the result will be displayed in a message box.

Note: The basic criteria of an email is that it must contain alphabets or numbers and special characters like ‘ . ‘ and ‘@’.

Python
# import modules
import tkinter as tk
from tkinter import messagebox
import re

# function to check valid email
def validate_email(email):
    email_pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
    if re.match(email_pattern, email):
        return True
    return False

# function called when Submit is clicked
def on_submit():
    email = email_entry.get()
    if not validate_email(email):
        messagebox.showerror("Invalid Input", 
                             "Email must contain '@' and '.' characters.")
    else:
        messagebox.showinfo("Valid Input", "Email is valid.")

# main Tkinter application window
root = tk.Tk()
root.title("Email Validation")
root.geometry("300x200")

# tkinter widgets
email_label = tk.Label(root, text="Email:")
email_label.pack()
email_entry = tk.Entry(root)
email_entry.pack()

# sumit buttion to check validity
submit_button = tk.Button(root, text="Submit", command=on_submit)
submit_button.pack()

root.mainloop()

Output:

Validating Entry Widget on Email

Validating Entry Widget on Email

Empty Value Validation: Required Field

In this example, we will create a Tkinter window that will validate that the input is not an empty value. This means that the user should not click the submit button without entering some value in the Entry widget.

Python
# import modules
import tkinter as tk
from tkinter import messagebox

# function to check valid entry
def validate_not_empty(value):
    if value.strip():
        return True
    return False

# function called when Submit is clicked
def on_submit():
    value = entry.get()
    if not validate_not_empty(value):
        messagebox.showerror("Invalid Input", 
                             "Field cannot be empty.")
    else:
        messagebox.showinfo("Valid Input", 
                            "Input is valid.")

# main Tkinter application window
root = tk.Tk()
root.title("Empty Value Validation")
root.geometry("300x200")

# tkinter widgets
label = tk.Label(root, text="Enter something:")
label.pack()
entry = tk.Entry(root)
entry.pack()

# sumit buttion to check validity
submit_button = tk.Button(root, text="Submit", command=on_submit)
submit_button.pack()

root.mainloop()

Output:


Validating Entry Widget not to be Empty


Validating Entry Widget not to be Empty

Conclusion

The Tkinter Entry widget is a fundamental tool for accepting user input in Python GUI applications. Validating this input is crucial to ensure that it meets specific criteria before processing. By implementing validation logic when a submit button is pressed, and displaying the result in a messagebox popup, you can provide immediate feedback to the user about the validity of their input. This article demonstrated how to validate numeric input, email addresses, and length constraints using Tkinter’s Entry widget, enhancing the robustness and user-friendliness of your applications.



Contact Us