Tkinter validation of user entry using call back function on keypress on focus in & out using filter
validate='key', is used to check for validation when any key is used. Check the other options for validate at the end of this tutorial.
validatecommand=(my_valid,'%S'), is used to trigger the callback function validate() by sending the input and getting the status as True or False. my_valid = my_w.register(validate) Register the callback function
import tkinter as tk
from tkinter import *
my_w = tk.Tk()
my_w.geometry("400x100") # Size of the window
my_w.title("www.plus2net.com") # Adding a title
def validate(u_input): # callback function
return u_input.isdigit()
my_valid = my_w.register(validate) # register
l1=tk.Label(my_w,text='Enter Number only')
l1.grid(row=1,column=1,padx=20,pady=20)
e1 = Entry(my_w,validate='key',validatecommand=(my_valid,'%S'))
e1.grid(row=1,column=2,padx=20)
my_w.mainloop() # Keep the window open
Alphnumeric only
Only numbers and alphabets are allowed, other chars will not be accepted. Here we are ony indicating the line inside the validate(u_input) function of above code.
Read more on isalnum() here.
def validate(u_input):
#return u_input.isdigit() # use other string functions.
return u_input.isalnum()
By using other string functions we can extend the validation to different requirments. Here is the list.
* To use whole string use %P instead of %S. For some checking we have to consider the whole string like istitle()
validatecommand=(my_valid,'%P')
Validating email address
Here we will use focusout event which will validate the email format. One button is kept which will be disabled if validation is not clear and will get enabled again if correct format is used for email address.
Here regular experssion is used to check the email format.
import tkinter as tk
from tkinter import *
my_w = tk.Tk()
import re
regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
my_w.geometry("400x100") # Size of the window
my_w.title("www.plus2net.com") # Adding a title
def validate(u_input):
if(re.search(regex,u_input) and u_input.isalpha):
print(True)
b1.config(state='active')
return True
else:
print(False)
b1.config(state='disabled')
return False
my_valid = my_w.register(validate)
l1=tk.Label(my_w,text='Email')
l1.grid(row=1,column=1,padx=5,pady=20)
e1 = Entry(my_w,validate='focusout',validatecommand=(my_valid,'%P'))
e1.grid(row=1,column=2,padx=10)
l2=tk.Label(my_w,text='Name')
l2.grid(row=1,column=3,padx=5,pady=20)
e2 = tk.Entry(my_w,width=10)
e2.grid(row=1,column=4)
b1 = tk.Button(my_w,text='Submit')
b1.grid(row=1,column=5)
my_w.mainloop() # Keep the window open
print(type(4.5))
List of validate options
focus
When entry widget get or lose focus
focusin
When entry widget get focus
focusout
When entry widget get focus
key
When entry widget keystroke changes the widget's contents