2009-06-19 35 views
1

Pythonで遊ぶ - tkInter - Entry widget - validatecommand(下記)を使用すると、最初に文字列> Maxがチェックされますが、テキストを入力し続けると、または初めて挿入した後に挿入しますか?何かアドバイス?Python tkInter Entry fun


#!/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:あなたはvalidateCommandまたはinvalidCommandのいずれかの中からエントリウィジェットを編集するとき

検証オプションもなしに自分自身を設定します。そのようなエディションは、検証されていたものを上書きします。あなたは、エントリウィジェットを編集したい場合は検証中に(例えば、{}に設定)、まだ検証オプションが設定されている、あなたはアイドルの後にコマンド

を含める必要があります{%のW設定-validate%V}

これをPythonにどのように翻訳するかわかりません。ここで

+0

'ワット= nametowidget(W)#Wは、名前ofvthe TKの方法で.nametowidgetウィジェット、()'と 'after_idle(ワットです。 config、{'validate':v}) ' –

1

(のpython経由でデスクトップアプリケーションを構築していないの外で)私は理由があるまさに確信しているが、私は勘を持っています。妥当性チェックは、エントリが編集されるたびに実行されます。私はいくつかのテストを行い、それが実際に実行されることを発見し、毎回検証中にあらゆる種類のことを行うことができます。何が正しく動作しなくなるかは、validatecommand関数内から編集するときです。これにより、validate関数の呼び出しはこれ以上終了しません。私はそれがもはやエントリー値やそれ以上の編集を認識しないと思う。

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

並べ替えのは、コンソールにやっているかを見ることができますので、私はprint文の束に投げました。ここで

は、あなたが渡すことができ、他の置換である:

%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. 
関連する問題