需要了解的重要一点是,Tkinter 只是嵌入式 Tcl 解释器的一个薄包装。这意味着由于两种语言的根本差异,有时会出现一些小的妥协。
TCL之道
在 Tcl 中进行输入验证时,您指定一个 Tcl 脚本而不仅仅是一个可调用函数。 Tcl 将扫描代码中的特殊字符序列(例如%P
, %S
等),并将它们替换为有关要验证的数据的信息。
当用 Tcl 编写时,您的代码可能如下所示:
entry .amount -validate key -validatecommand {
expr {[string is int %P] || [string length %P]==0}
}
或者,使用 Tcl 函数:
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}
Python 方式
Python 没有一种简单的方法来将代码作为字符串传递,即使有,Tcl 也无法理解它。相反,在 python 中,您必须传递对callable https://stackoverflow.com/questions/111234/what-is-a-callable-in-python-- 通常是对函数或方法的引用。
为了传递 python 需要可调用的特殊替换字符,您必须创建一个 Tcl 过程来充当 python 函数的代理。当您调用register
功能。
proc = creditor.register(check_the_input_only_allows_digits_only)
amount.config(validate = "key", validatecommand = (proc,"%P"))
如果不使用这些字符,则无需注册该命令。例如,以下代码是调用不带参数的函数的有效方法:
def check_the_input_only_allows_digits_only():
...
amount.config(validate = "key",validatecommand = check_the_input_only_allows_digits_only)
当然,传递的值是%P
而其他特殊字符序列使得验证功能如此强大。