【问题标题】:Entry Validation Extra Arguments条目验证额外参数
【发布时间】:2013-08-13 20:14:34
【问题描述】:

我有一组在 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 接受不包含在this answer 提供的列表中的参数,重复如下:

# 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) 以及尝试的输入。如何向不在该列表中的验证命令添加参数?

【问题讨论】:

  • “条目的位置”是什么意思?是否要传入pos 的值?
  • @Bryan Oakley,没错。

标签: python tkinter


【解决方案1】:

你给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)

【讨论】:

  • 这很棒。谢谢你。请问为什么命令必须先注册才能设置为validatecommand函数?起初我认为它可能是使它成为一个有效的回调,但 lambda 函数也可以工作,至少对于不接受特殊参数的东西。此外,“%P”字符串中的格式是否代表新输入?我不明白字符串如何成为有效的参数关键字。我认为关键字必须是变量名。
  • 现在这很奇怪。调整我的代码后,我尝试了你的答案,并在 VE 中调用了一个返回字符串的 pos,而不是 pos 在 self.entryDict.keys() 中的元组值。从 pos 字符串中提取数据来改造 pos 元组不是问题,但是是什么将它强制转换为字符串呢?它甚至不返回与 str(pos) 相同的字符串。
  • 这个数据被传递给底层的 Tcl 解释器,它不知道 python 数据类型。在 Tcl 中“一切都是字符串”,所以翻译发生在 python/Tcl 边界。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-02
  • 1970-01-01
  • 2014-07-07
  • 2015-07-01
  • 2019-01-29
  • 1970-01-01
  • 2021-07-21
相关资源
最近更新 更多