Tkinter 的 Entry 对其进行输入的文本进行实时的validation
1 try: 2 # python 3.x 3 import tkinter as tk 4 except ImportError: 5 # python 2.x 6 import Tkinter as tk 7 8 class Example(tk.Frame): 9 10 def __init__(self, parent): 11 tk.Frame.__init__(self, parent) 12 13 # valid percent substitutions (from the Tk entry man page) 14 # %d = Type of action (1=insert, 0=delete, -1 for others) 15 # %i = index of char string to be inserted/deleted, or -1 16 # %P = value of the entry if the edit is allowed 17 # %s = value of entry prior to editing 18 # %S = the text string being inserted or deleted, if any 19 # %v = the type of validation that is currently set 20 # %V = the type of validation that triggered the callback 21 # (key, focusin, focusout, forced) 22 # %W = the tk name of the widget 23 24 vcmd = (self.register(self.onValidate), 25 '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') 26 self.entry = tk.Entry(self, validate="key", validatecommand=vcmd) 27 self.text = tk.Text(self, height=10, width=40) 28 self.entry.pack(side="top", fill="x") 29 self.text.pack(side="bottom", fill="both", expand=True) 30 31 def onValidate(self, d, i, P, s, S, v, V, W): 32 self.text.delete("1.0", "end") 33 self.text.insert("end","OnValidate:\n") 34 self.text.insert("end","d='%s'\n" % d) 35 self.text.insert("end","i='%s'\n" % i) 36 self.text.insert("end","P='%s'\n" % P) 37 self.text.insert("end","s='%s'\n" % s) 38 self.text.insert("end","S='%s'\n" % S) 39 self.text.insert("end","v='%s'\n" % v) 40 self.text.insert("end","V='%s'\n" % V) 41 self.text.insert("end","W='%s'\n" % W) 42 43 # Disallow anything but lowercase letters 44 valid = (S.lower() == S) 45 if not valid: 46 self.bell() 47 return valid 48 49 if __name__ == "__main__": 50 root = tk.Tk() 51 Example(root).pack(fill="both", expand=True) 52 root.mainloop()