Creating validated widget classes
As you can see, adding even very simple validation to Tkinter widgets involves several steps with some less-than-intuitive logic. Adding validation to even a fraction of our widgets could get quite verbose and ugly. However, we learned in the previous chapter that we can improve on Tkinter widgets by subclassing them to add new configuration and functionality. Let's see if we can apply this technique to widget validation by creating validated versions of Tkinter's widget classes.
For example, let's implement our five-character entry again, this time as a subclass of ttk.Entry
, like so:
# five_char_entry_class.py
class FiveCharEntry(ttk.Entry):
"""An Entry that truncates to five characters on exit."""
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.error = tk.StringVar()
self.configure(
validate='all',
validatecommand...