What is the recommended technique for interactively validating content in a tkinter Entry
widget?
I've read the posts about using validate=True
and validatecommand=command
, and it appears that these features are limited by the fact that they get cleared if the validatecommand
command updates the Entry
widget's value.
Given this behavior, should we bind on the KeyPress
, Cut
, and Paste
events and monitor/update our Entry
widget's value through these events? (And other related events that I might have missed?)
Or should we forget interactive validation altogether and only validate on FocusOut
events?
Best Answer
The correct answer is, use the
validatecommand
attribute of the widget. Unfortunately this feature is severely under-documented in the Tkinter world, though it is quite sufficiently documented in the Tk world. Even though it's not documented well, it has everything you need to do validation without resorting to bindings or tracing variables, or modifying the widget from within the validation procedure.The trick is to know that you can have Tkinter pass in special values to your validate command. These values give you all the information you need to know to decide on whether the data is valid or not: the value prior to the edit, the value after the edit if the edit is valid, and several other bits of information. To use these, though, you need to do a little voodoo to get this information passed to your validate command.
Note: it's important that the validation command returns either
True
orFalse
. Anything else will cause the validation to be turned off for the widget.Here's an example that only allows lowercase. It also prints the values of all of the special values for illustrative purposes. They aren't all necessary; you rarely need more than one or two.
For more information about what happens under the hood when you call the
register
method, see Why is calling register() required for tkinter input validation?For the canonical documentation see the Validation section of the Tcl/Tk Entry man page