Вот пример кода, который ограничит ввод до 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.