Let's assume that we have a form that asks for a username. We want users to input only alphabetical or space characters in the name. Thus, a number of special characters should not be allowed, as shown in the following screenshot of the widget:
This is clearly a case for the key validation mode because we want to check whether an entry is valid after every keypress. The percent substitution that we need to check is %S because it yields the text string being inserted or deleted in
the Entry widget. Therefore, the code that validates the Entry widget is as follows (see the 10.05_key_validation.py code):
import tkinter as tk
class KeyValidationDemo():
def __init__(self):
root = tk.Tk()
tk.Label(root, text='Enter your name / only alpabets & space
allowed').pack()
vcmd = (root.register(self.validate_data), '%S')
invcmd = (root.register(self.invalid_name), '%S')
tk.Entry(root, validate="key",validatecommand=vcmd,
invalidcommand=invcmd).pack(pady=5, padx=5)
self.error_message = tk.Label(root, text='', fg='red')
self.error_message.pack()
root.mainloop()
def validate_data(self, S):
self.error_message.config(text='')
return (S.isalpha() or S == ' ')
def invalid_name(self, S):
self.error_message.config(text='Invalid character %s
name can only have alphabets and spaces' % S)
app = KeyValidationDemo()
The description of the preceding code is as follows:
- We first register two options, namely validatecommand ( vcmd ) and invalidcommand ( invcmd ).
- In the example, validatecommand is registered to call the validate_data method, and the invalidcommand option is registered to call another method named invalid_name.
- The validatecommand option specifies a method that needs to be evaluated, which will validate the input. The validation method must return a Boolean value, where True signifies that the data entered is valid, and a False return value signifies that the data is invalid.
- In case the validate method returns False (invalid data), no data is added to the Entry widget and the script registered for invalidcommand is evaluated. In our case, a False validation will call the invalid_name method. The invalidcommand method is generally responsible for displaying error messages or setting back the focus to the Entry widget.