Focus-out validation mode demo

The previous example demonstrated validation in the key mode. This means that the validation method was called after every keypress to check whether an entry was valid.

However, there are situations where you might want to check the entire string entered into the widget rather than checking individual keystroke entries.

For example, when an Entry widget accepts a valid email address, we would ideally like to check the validity after the user has entered the entire email address and not after every keystroke entry. This will qualify for a validation in the focusout mode.

Check out 10.06_focus_out_validation.py for a demonstration of email validation in the focusout mode, which gives us the following GUI:

The code for the aforementioned demo is as follows:

import tkinter as tk
import re

class FocusOutValidationDemo():
def __init__(self):
self.master = tk.Tk()
self.error_message = tk.Label(text='', fg='red')
self.error_message.pack()
tk.Label(text='Enter Email Address').pack()
vcmd = (self.master.register(self.validate_email), '%P')
invcmd = (self.master.register(self.invalid_email), '%P')
self.email_entry = tk.Entry(self.master, validate="focusout",
validatecommand=vcmd, invalidcommand=invcmd)
self.email_entry.pack()
tk.Button(self.master, text="Login").pack()
tk.mainloop()

def validate_email(self, P):
self.error_message.config(text='')
x = re.match(r"[^@]+@[^@]+.[^@]+", P)
return (x != None)

def invalid_email(self, P):
self.error_message.config(text='Invalid Email Address')
self.email_entry.focus_set()

app = FocusOutValidationDemo()

This code has a lot of similarities to the previous validation example. However, note the following differences:

  • The validate mode is set to focusout in contrast to the key mode in the previous example. This means that the validation will be done only when the Entry widget loses focus. The validation occurs when you hit the Tab key. Thus, the input box does not lose its focus in case the input is invalid.
  • This program uses data provided by the %P percentage substitution, while the previous example used %S. This is understandable because %P provides the value entered in the Entry widget, but %S provides the value of the last keystroke.
  • This program uses regular expressions to check whether the entered value corresponds to a valid email format. Validation usually relies on regular expressions. A whole lot of explanation is required to cover this topic, but that is beyond the scope of this book. For more information on regular expression modules, visit http://docs.python.org/3.6/library/re.html.

This concludes our discussion on input validation in Tkinter. Hopefully, you should now be able to implement input validation to suit your custom needs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.137.59