How to validate text entry in a form in Tkinter
Overview
We can validate a text entry in Tkinter with the help of callback functions of button widget in tkinter.
The Button class
The Button class is used to create buttons in tkinter.
The syntax to create a button is as follows:
ttk.Button(parent, options)
Parameters
parent: This is the parent component on which the button will be placed.options: There are a lot of options. Some of the important options we use in this answer are as follows:
| Option | Description |
|---|---|
text |
The text to display on the button. |
padx |
Padding to the button in x or horizontal direction. |
pady |
Padding to the button in y or vertical direction. |
command |
The callback function to be called. |
Let’s learn this with the help of an example.
We build a simple GUI using Python Tkinter. Firstly, we create a simple interface to accept the user input and a submit button. When the user clicks on the submit button, a validation function is invoked.
Example
import tkinter as tk
from tkinter import messagebox
window_screen = tk.Tk()
window_screen.title('Validation Demo')
window_screen.geometry('300x200')
def validation():
text = text_tf.get()
msg = "The input text is correct"
if len(text) == 0:
msg = "The text can\'t be empty"
elif len(text) > 20:
msg = "The text can\'t be greater than 20 characters"
messagebox.showinfo('message', msg)
frame = tk.Frame(window_screen, padx=10, pady=10)
frame.pack(pady=20)
tk.Label(frame, text='Enter Text').grid(row=0, column=0)
text_tf = tk.Entry(frame, font=('calibre',10,'normal'))
text_tf.grid(row=0, column=1)
tk.Button(frame, text='Submit', pady=10, padx=20, command=validation).grid(row=1, columnspan=2)
window_screen.mainloop()
Explanation
-
Lines 1–2: We import the relevant dependencies.
-
Line 4: We create an instance of
Tk()calledwindow_screen. -
Line 5: We set the title of the
window_screenusing thetitle()method. -
Line 6: We set the shape of the
window_screenusing thegeometry()method. -
Lines 8–17: We define a method called
validation()which gets called when thesubmitbutton is clicked.-
Line 9: We retrieve the content of the text entry using the
get()method. -
Line 10: A variable called
msgis defined that contains the message to be shown to the user after the validation. -
Lines 12–15: We check if the input text is empty or more than
20characters. -
Line 17: We use the message box to show the validation result to the user.
-
-
Line 19: A frame called
frameis created. -
Line 22: A label for the text entry widget is created.
-
Line 23: A text entry widget is created with the help of the
Entryclass. -
Line 25: A button is created with the
commandparameter set to thevalidationfunction. Thevalidationfunction is invoked once the button is clicked.
Free Resources