python - Tkinter 条目验证 -- 如何使用 %W

标签 python tkinter

我可以通过如图所示的构造变量来引用小部件,但根据打印的内容,W 也应该可以工作,因为显然 Wnew_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'>

关于python - Tkinter 条目验证 -- 如何使用 %W,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57668833/

相关文章:

python - 如何限制将特定分支 merge 到 Gitlab 中的其他分支?

python - 如何创建带有可滚动文本小部件的 GUI

python - 在 Ubuntu 上的 TextBox Tkinter Python 中打印

python - 如何让 tkinter 窗口在几秒钟延迟后自动关闭?

python - 是否可以只运行 asyncio 事件循环的一个步骤

Python 程序意外终止

Python/Django AMQP?

python - 在复平面上绘制图形

python - 是否可以通过 ctypes 通过引用传递 python 字符串?

python - 在 Python 中实现比较类的 OOP 方法