使用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()
有帮助吗?

解决方案

来自Tk人

  

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

     空闲{%W config -validate%v}

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

其他提示

以下是将输入限制为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.

我确定原因究竟是什么,但我有预感。每次编辑条目时都会进行验证检查。我做了一些测试,发现它确实执行了,并且每次都可以在验证过程中做各种各样的事情。导致它停止正常工作的原因是从validatecommand函数中编辑它。这导致它停止再调用validate函数。我想它不再能够识别对条目值的进一步编辑。

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top