The important thing to know is that Tkinter is just a thin wrapper around an embedded Tcl interpreter. That means there are sometimes small compromises due to fundamental differences in the two languages.
The Tcl Way
When doing input validation in Tcl you specify a Tcl script rather than just a callable function. Tcl will scan the code for special character sequences (such as %P
, %S
, etc), and substitute them with information about the data to be validated.
When written in Tcl your code might look something like this:
entry .amount -validate key -validatecommand {
expr {[string is int %P] || [string length %P]==0}
}
Or, using a Tcl function:
proc check_the_input_only_allows_digits_only {P} {
expr {[string is int P] || [string length P] == 0}
}
entry .amount \
-validate key \
-validatecommand {check_the_input_only_allows_digits_only %P}
The Python Way
Python doesn't have an easy way to pass around code as a string, and even if it did Tcl wouldn't understand it. Instead, in python you must pass a reference to a callable -- typically a reference to a function or method.
In order to pass in those special substitution characters where python expects a callable, you must create a Tcl procedure which acts as a proxy to your python function. This command is created when you call the register
function.
proc = creditor.register(check_the_input_only_allows_digits_only)
amount.config(validate = "key", validatecommand = (proc,"%P"))
If you do not use these characters, you don't need to register the command. For example, the following code is a valid way to call a function that takes no parameters:
def check_the_input_only_allows_digits_only():
...
amount.config(validate = "key",validatecommand = check_the_input_only_allows_digits_only)
Of course, being passed the values for %P
and the other special character sequences is what makes the validation function so powerful.