【问题标题】:Python tkInter Entry funPython tkInter 入门乐趣
【发布时间】:2010-11-04 10:08:16
【问题描述】:

使用 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()

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    From the Tk man:

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

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

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

    【讨论】:

    • w = nametowidget(W) # W is the name ofvthe widget, .nametowidget is a method of Tk()after_idle(w.config, {'validate': v})
    【解决方案2】:

    这是一个将输入限制为 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】:

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

      lgal Serban 似乎掌握了发生这种情况的幕后信息。

      【讨论】:

        猜你喜欢
        • 2017-02-08
        • 2016-11-05
        • 2010-12-24
        • 2013-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多