Limitting the Contents of an Entry Widget in Tkinter
James Stroud
jstroud at ucla.edu
Sat Jan 14 18:01:37 EST 2006
Dustan wrote:
> How do I limit what the user can enter in an Entry Widget? I know I can
> set it to display '*' to hide a password, but what I want to do is
> limit the contents to numeric characters. What is the easiest way of
> doing this?
>
You can check the source of tkSimpleDialog.askfloat, which, in my
opinion, is pretty lazy. It checks after everything is entered.
Cooler is to intercept events and check them real-time. It gets
complicated but I find the resulting gui to be much more "user-friendly"
and intuitive.
The key events to catch for an entry are <Key> and <ButtonRelease-2>
(pasting). Other types of pasting (e.g. ctrl-v) may also be used and you
can code these to your preference. When you intercept these events, a
good way is to check and see what would happen to the entry by testing
the result of the key press without modifying the entry. Return "break"
if the result does not meet your criteria (float, int, even, odd, etc).
If it does meet your criteria, update the Entry and return "break".
Remember to process special keys, like "Delete" and "Tab". You can
modify their behavior to your taste. For "Tab" and "<Shift-Tab>", look at
awidget.tk_focusNext().focus_set()
awidget.tk_focusPrev().focus_set()
A list of keysyms is at
http://infohost.nmt.edu/tcc/help/pubs/tkinter/key-names.html
These can be accesed by the Event.keysym attribute. Keysyms seem to be
somewhat platform independent and seem to correspond to events pretty
well. For pasting, you will want to access the pasteboard(s) via
Event.widget.selection_get(selection='PRIMARY')
Event.widget.selection_get(selection='CLIPBOARD')
in that order, using try/except.
James
More information about the Python-list
mailing list