python - Tkinter validatecommand 命令会破坏参数类型吗?

标签 python validation tkinter user-input tkinter-entry

我一直在尝试通过附加提供条目和预期类型(来自内置 type() 函数的 Type 类对象)的处理程序函数,在 Entry 小部件中进行一些类型检查。一切都运行良好,只是 validate 命令似乎将 Type 对象的类型从 Type 更改为字符串,这并非不可克服,但让我很好奇发生了什么。

请参阅下面的最小可重现示例 - 请注意,处理程序在 native python 中正确传递了类型对象,但使用 tkinter,类型对象的类型更改为字符串。

#NATIVE PYTHON

variable = 'HelloWorld'
vartype = type(variable)

print('VALUE OF VARTYPE: ', vartype, 'TYPE OF VARTYPE: ', type(vartype))

def handler(variable,vartype):
    print('VALUE OF VARTYPE: ', vartype, 'TYPE OF VARTYPE: ', type(vartype))

handler(variable,vartype)

#TKINTER VALIDATE HANDLER

import tkinter as tk

top = tk.Tk()
frame = tk.Frame(top)
frame.pack()
vcmd =frame.register(handler)
entry = tk.Entry(frame, validate = 'focusout', validatecommand = (vcmd,"%P",vartype))
entry.pack()

top.mainloop()

解决这个问题的方法是为处理程序创建一个 lambda 包装器,以避免将类型对象传递给 validatecommand:


#NATIVE PYTHON

variable = 'HelloWorld'
vartype = type(variable)


print('VALUE OF VARTYPE: ', vartype, 'TYPE OF VARTYPE: ', type(vartype))

def handler(*variable,vartype=vartype):
    print('VALUE OF VARTYPE: ', vartype, 'TYPE OF VARTYPE: ', type(vartype))

handler(*variable,vartype=vartype)

#TKINTER VALIDATE HANDLER

import tkinter as tk

top = tk.Tk()
frame = tk.Frame(top)
frame.pack()
vcmd =frame.register(lambda *args, vartype=vartype : handler(*args,vartype=vartype))
entry = tk.Entry(frame, validate = 'focusout', validatecommand = (vcmd,"%P"))
entry.pack()

top.mainloop()

但是,我仍然有些不满意,不知道第一次迭代发生了什么 - 我在那里做错了什么?

最佳答案

All works well except it appears the validatecommand changes the type of the Type object from Type to a string, which is not insurmountable but has made me curious what's going on.... However, I have still somewhat unsatisfied not knowing what happened with the first iteration - what am I doing wrong there?

你没有做错任何事,除了试图做一些 tkinter 设计上不支持的事情。

Tkinter 是嵌入式 Tcl 解释器的面向对象包装器。该嵌入式解释器对 python 对象一无所知,因此无法将 python 对象传递到 Tcl 解释器或从 Tcl 解释器检索。当您传递 python 函数作为参数时,tkinter 必须将其转换为字符串,然后才能由 Tcl 解释器处理。

这就是为什么必须向 Tcl 解释器注册 python 函数的原因。 Tkinter 将创建一个内部 Tcl 函数,该函数知道如何调用 python 函数。然后可以在 Tcl 解释器内部使用该函数的名称。

关于python - Tkinter validatecommand 命令会破坏参数类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66512265/

相关文章:

python - 交错两个 numpy 1D 阵列用于立体声音频输出

python - shell_plus 安装 Django 时出现错误 - ImportError : cannot import name 'Type

javascript - HTML 验证/脚本 JS

asp.net - 验证失败后如何防止页面跳转到顶部位置?

Python Tkinter 交换选项菜单选择

python-3.x - 如何在 tkinter OptionMenu 中允许多个选择?

python - 从 zipfile 加载 pickle 文件

python - 按一周中的几天进行分箱。 Pandas Python Matplotlib

java - 如何使用单选按钮根据用户输入执行不同的方程?

linux - 无法打开 Pyinstaller 的输出文件