Python tkInter 输入框功能

3 投票
3 回答
6746 浏览
提问于 2025-04-15 12:22

我在玩Python的tkInter库中的Entry控件。当我使用validatecommand(下面的代码)时,第一次输入的字符串超过最大值时会进行检查,但之后继续输入文本时就不再检查了——在第一次之后没有删除或插入的操作?有什么建议吗?(除了不通过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()

3 个回答

1

我不太确定具体原因,但我有个猜测。每次编辑输入框时,都会进行一次验证检查。我做了一些测试,发现每次确实会执行这个检查,并且在验证过程中可以做很多事情。但是,当你在validatecommand函数内部进行编辑时,就会导致它不再正常工作。这是因为它停止调用验证函数了。我想它可能不再识别输入框的进一步编辑了,或者是其他什么原因。

lgal Serban似乎对这个问题的背后原因有一些了解。

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.
3

来自Tk的说明:

在使用验证选项时,如果你在验证命令(validateCommand)或无效命令(invalidCommand)中编辑了输入框(entry widget),那么验证选项会自动设置为“无”。这意味着你所做的编辑会覆盖正在进行的验证。如果你想在验证过程中编辑输入框(比如把它设置为空{}),但仍然希望保持验证选项有效,你需要在空闲时包含这个命令:

在空闲时执行 {%W config -validate %v}

我不知道怎么把这个翻译成Python代码。

撰写回答