3

玩 Python - tkInter - Entry 小部件 - 当我使用 validatecommand(如下)时,第一次检查字符串 > Max,但是当我继续输入文本时检查步骤 - 第一次后没有删除或插入?有什么建议吗?(除了不通过 python 构建桌面应用程序)


#!/usr/bin/env python
from Tkinter import *

class MyEntry(Entry):

    def __init__(self, master, maxchars):
        Entry.__init__(self, master, validate = "key",    validatecommand=self.validatecommand)
        self.MAX = maxchars

    def validatecommand(self, *args):
        if len(self.get()) >= self.MAX:
            self.delete(0,3)
            self.insert(0, "no")
        return True

if __name__ == '__main__':
    tkmain = Tk()
    e = MyEntry(tkmain, 5)
    e.grid()
    tkmain.mainloop()
4

3 回答 3

3

来自 Tk 人

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

空闲后 {%W config -validate %v}

不知道如何将其翻译成python。

于 2009-06-19T21:32:54.287 回答
3

这是一个将输入限制为 5 个字符的代码示例:

import Tkinter as tk

master = tk.Tk()

def callback():
    print e.get()

def val(i):
    print "validating"
    print i

    if int(i) > 4:
        print "False"
        return False
    return True

vcmd = (master.register(val), '%i')

e = tk.Entry(master, validate="key", validatecommand=vcmd)
e.pack()

b = tk.Button(master, text="OK", command=lambda: callback())
b.pack()

tk.mainloop()

我扔了一堆打印语句,这样你就可以在控制台中看到它在做什么。

以下是您可以传递的其他替换:

   %d   Type of action: 1 for insert, 0  for  delete,  or  -1  for  focus,
        forced or textvariable validation.

   %i   Index of char string to be inserted/deleted, if any, otherwise -1.

   %P   The value of the entry if the edit is allowed.  If you are config-
        uring  the  entry  widget to have a new textvariable, this will be
        the value of that textvariable.

   %s   The current value of entry prior to editing.

   %S   The text string being inserted/deleted, if any, {} otherwise.

   %v   The type of validation currently set.

   %V   The type of validation that triggered the callback (key,  focusin,
        focusout, forced).

   %W   The name of the entry widget.
于 2010-12-07T02:21:21.117 回答
1

我确定确切的原因是什么,但我有预感。每次编辑条目时都会进行验证检查。我做了一些测试,发现它确实执行,并且每次验证期间都可以做各种事情。导致它停止正常工作的原因是当您从 validatecommand 函数中对其进行编辑时。这会导致它停止进一步调用 validate 函数。我猜它不再识别对条目值或其他内容的进一步编辑。

lgal Serban 似乎有关于为什么会发生这种情况的幕后信息。

于 2009-06-19T21:25:00.450 回答