Python 条目验证附加参数

Python 条目验证附加参数,python,tkinter,Python,Tkinter,我在for循环中创建了一组输入框,并将其记录在一个字典中,我希望对其进行独立验证。创建它们的循环如下所示: vcmd = (self.register(self.VE), '%P') for pos in [(i,j) for i in range(9) for j in range(9)]: self.inputDict[pos] = tk.StringVar() self.entryDict[pos] = tk.Entry(font = ('A

我在for循环中创建了一组输入框,并将其记录在一个字典中,我希望对其进行独立验证。创建它们的循环如下所示:

vcmd = (self.register(self.VE), '%P')
for pos in [(i,j) for i in range(9) for j in range(9)]:
            self.inputDict[pos] = tk.StringVar()
            self.entryDict[pos] = tk.Entry(font = ('Arial', 20, 'bold'),
                                           textvariable = self.inputDict[pos],
                                           borderwidth = 1, width = 2,
                                           justify = 'center',
                                           validatecommand = vcmd,
                                           validate = 'key')
self.VE的代码如下:

def VE(self, P, pos):
    if P in [str(i) for i in map(chr,range(49,58))]:
        self.solution.insertVal(P,pos)
    elif P == '': self.solution.removeVal(pos)
    return P in [str(i) for i in map(chr,range(49,58))]+['']
我的问题是,我不知道如何让VE获取未包含在列表中的参数,重复如下:

# valid percent substitutions (from the Tk entry man page)
# %d = Type of action (1=insert, 0=delete, -1 for others)
# %i = index of char string to be inserted/deleted, or -1
# %P = value of the entry if the edit is allowed
# %s = value of entry prior to editing
# %S = the text string being inserted or deleted, if any
# %v = the type of validation that is currently set
# %V = the type of validation that triggered the callback
#      (key, focusin, focusout, forced)
# %W = the tk name of the widget

我相信我需要对定义
vcmd
的行进行更改,但我不知道要做什么更改,以允许验证命令占据条目的位置(即
pos
的值)以及尝试的输入。如何向验证命令添加不在该列表中的参数?

您给
validatecommand
的值是已注册命令和要传递给该命令的任何参数的元组。因此,您可以这样做:

    vcmd = self.register(self.VE)

    for pos in ...:
        self.entryDict[pos] = tk.Entry(..., 
                                       validatecommand=(vcmd, "%P", pos), 
                                       ...)
    ...

def VE(self, P, pos):
    print "P: %s pos: %s" % (P, pos)

你所说的“条目的位置”是什么意思?你想传入
pos
的值吗?@Bryan Oakley,没错。这很好。非常感谢。我想问一下,为什么必须先注册该命令,然后才能将其设置为validatecommand函数?起初我认为这可能是为了使它成为一个有效的回调函数,但lambda函数也可以工作,至少对于不需要特殊参数的对象是如此。另外,'%P'字符串中的格式是否代表新输入?我不明白字符串怎么可能是有效的参数关键字。我以为关键字必须是变量名。现在这很奇怪。在调整代码后,我尝试了您的答案,并在VE中调用pos,该调用返回一个字符串,而不是pos在self.entryDict.keys()中接受的元组值。从pos字符串中提取数据以重组pos元组不是问题,但是什么强迫它成为字符串?它甚至没有返回与str(pos)相同的字符串,这些数据被传递给底层的Tcl解释器,而Tcl解释器对python数据类型一无所知。在Tcl中,“一切都是字符串”,因此转换发生在python/Tcl边界。