Python 如何使用验证程序函数中的小部件名称?

Python 如何使用验证程序函数中的小部件名称?,python,tkinter,widget,Python,Tkinter,Widget,我发现这个代码: 我需要使用实例(%W),但它是一个字符串。我需要这样的东西: import tkinter as tk # python 3.x # import Tkinter as tk # python 2.x class Example(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) vcmd = (self.register(self.onVa

我发现这个代码:

我需要使用实例(%W),但它是一个字符串。我需要这样的东西:

import tkinter as tk  # python 3.x
# import Tkinter as tk # python 2.x

class Example(tk.Frame):

    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        vcmd = (self.register(self.onValidate),
                '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
        self.entry = tk.Entry(self, validate="key", validatecommand=vcmd)
        self.text = tk.Text(self, height=10, width=40)
        self.entry.pack(side="top", fill="x")
        self.text.pack(side="bottom", fill="both", expand=True)

    def onValidate(self, d, i, P, s, S, v, V, W):
        print type(W) #This gives <string>
        W = instance(W) #Something to convert the string to an instance like int()
        W.get()
        W.insert('Some text',0)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()
将tkinter作为tk#python 3.x导入
#将Tkinter作为tk#python 2.x导入
类示例(tk.Frame):
定义初始化(自身,父级):
tk.Frame.\uuuu init\uuuuu(自,父)
vcmd=(self.register(self.onValidate)),
“%d”、“i”、“P”、“s”、“s”、“v”、“v”、“W”)
self.entry=tk.entry(self,validate=“key”,validatecommand=vcmd)
self.text=tk.text(self,高度=10,宽度=40)
自进式包装(side=“top”,fill=“x”)
self.text.pack(side=“bottom”,fill=“both”,expand=True)
def onValidate(自我、d、i、P、s、s、v、v、W):
打印类型(W)#这会
W=instance(W)#将字符串转换为int()等实例的内容
得到
W.insert('某些文本',0)
如果名称=“\uuuuu main\uuuuuuuu”:
root=tk.tk()
示例(root).pack(fill=“both”,expand=True)
root.mainloop()
我需要一种方法来修改附加了valitation函数的小部件,因为register方法只以字符串形式给出小部件的路径或指针。但是我需要修改这个小部件

我一直在考虑将所有小部件放在一个名为“instance”的列表中,然后创建一个“for w in instances”,并将所有小部件与验证器函数的%w进行比较,直到它找到相同的小部件名称,然后修改列表中的对象


有没有更简单的方法?谢谢你们

验证功能不是为您在验证期间修改小部件的内容而设计的

从:

在validateCommand或invalidCommand中编辑条目小部件时,validate选项也将自身设置为none。此类版本将覆盖正在验证的版本。如果您希望在验证期间编辑条目小部件(例如,将其设置为{}),并且仍然设置了validate选项,那么应该包括以下命令

也就是说,如果需要,可以使用方法
nametowidget
将小部件名称转换为小部件引用,您可以通过任何小部件调用该方法

def onValidate(self, d, i, P, s, S, v, V, W):
    widget = self.nametowidget(W)
    ...

非常感谢你!
def onValidate(self, d, i, P, s, S, v, V, W):
    widget = self.nametowidget(W)
    ...