2009-06-19 66 views
1

玩弄Python - tkInter - Entry小部件 - 当我使用validatecommand(下面)时,检查发生在字符串> Max的第一次,但是当我继续输入文本时检查步骤 - 没有删除或在第一次后插入?有什么建议? (未建立通过Python桌面应用程序之外)Python tkInter条目乐趣


#!/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

From the Tk man

Validate选项也将自身设置为无,当你无论从validateCommand或invalidCommand内编辑的条目小部件。这些版本将覆盖正在验证的版本。如果您希望编辑录入组件验证过程中(例如将其设置为{}),并且仍然有验证选项设置,则应该包括命令

闲置后{%的W配置-validate%V}

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

+0

`W = nametowidget(W)#W是名称ofvthe插件,.nametowidget是Tk的的方法()`和`after_idle(瓦特config,{'validate':v})` – 2012-08-01 06:59:13

1

我敢肯定的原因是什么,但我有一种预感。每次编辑条目时都会进行验证检查。我做了一些测试,发现它确实执行,并且可以在每次验证过程中做各种事情。什么导致它停止正常工作是当你从validatecommand函数中编辑它时。这导致它停止进一步调用验证函数。我想它不再认可对输入值的进一步编辑或其他东西。

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

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.