python - Tkinter 条目验证——如何使用 %W
问题描述
我可以通过如图所示的构造变量来引用小部件,但根据打印的内容,W
显然也应该可以工作,W
并且new_user_input
两者都引用小部件名称。几天来,我一直在使用 Tkinter 的内置验证,这是我一直遇到的唯一问题。%P
按预期工作,但%W
没有。我不知道我做错了什么。我在一个类中使用它并将其拉出以简化代码,但错误消息是相同的。
import tkinter as tk
def validate1(W, P):
print("W is", W)
print("new_user_input is", new_user_input)
all_users = ["Bob", "Nancy"]
valid = P not in all_users
print("valid is", valid)
if valid is False:
new_user_input.bell() # works
W.delete(0,tk.END) # doesn't work
return valid
root = tk.Tk()
vcmd1 = (root.register(validate1), "%W", "%P")
new_user = tk.Label(
root,
text="New user name:")
new_user_input = tk.Entry(
root,
validate="focusout",
validatecommand=vcmd1)
new_user.grid()
new_user_input.grid()
tk.Entry(root).grid()
root.mainloop()
output:
W is .15065808
new_user_input is .15065808
valid is False
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\LUTHER\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:\tkinter_code\example_code\widget_variable_in_tkinter_validation.py",
line 13, in validate1
W.delete(0,tk.END)
AttributeError: 'str' object has no attribute 'delete'
解决方案
W
返回一个字符串。您可以通过以下方式检查type(W)
:
print("W is", W, type(W))
#W is .!entry <class 'str'>
要获取实际的小部件对象,请使用nametowidget
方法:
def validate1(W, P):
widget = root.nametowidget(W)
print("W is", widget, type(widget))
#W is .!entry <class 'tkinter.Entry'>
推荐阅读
- jq - 当其中一个值包含反斜杠时,jq 无法解析
- oracle - 解压缩/处理存储在 Oracle 文件夹中的大文件 gz
- python - 从自定义 PyQt5 QWidget 继承不调用父方法
- botframework - 一次将 1:1 Teams 机器人部署到所有用户
- javascript - 关于在对数组进行排序之前更改数组值的问题
- spring - Spring actuator/health 导致 HTTP 400 错误请求,JSON 解析错误
- webstorm - 如何从控制器切换到 html 代码?
- reactjs - 定义组件类型
- c# - 如何将引用类型分配给 c# 中的结构
- javascript - React Hook 的状态没有更新