The entry widget has options specifically for this sort of thing. You can set up a call back that will validate input, and reject any input that violates the constraints.
Here's a working example that limits the username to 10 characters, and password to 4:
import Tkinter as tk
def limitSize(new_value, max_len):
return True if len(new_value) <= int(max_len) else False
root = tk.Tk()
_limitSize = root.register(limitSize)
username = tk.Entry(root, validate="key", validatecommand=(_limitSize, '%P', 10))
password = tk.Entry(root, validate="key", validatecommand=(_limitSize, '%P', 4))
username.pack(fill="x")
password.pack(fill="x")
root.mainloop()
The validate
option specifies when the validation is done. "key"
causes the validation to be done on every keypress. Other values are relatively self-explanatory: "none", "focus", "focusin", "focusout", or "all".
The validatecommand
option specifies a tuple that requires a command that has been registered with the underlying tcl interpreter, and zero or more arguments. Tkinter has many special arguments that get replaced with information you can use to do the validation. In the above example, "%P" gets replaced with the value of the entry widget if the edit is allowed. You also have access to the type of edit (insert or delete), just the new text being inserted, and a few other things.
In this case we only care about the value if the edit is allowed. The callback is required to always return either True
or False
. If True
is returned, the modification is allowed, and if False
, the modification is disallowed.
One important thing to know: the values passed to the function will be converted to strings. That is why in the above example max_len
is converted to an int before doing the comparison.
For a slightly more in-depth example, see this answer: https://stackoverflow.com/a/4140988/7432