Limitting the Contents of an Entry Widget in Tkinter

D

Dustan

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?
 
J

James Stroud

Dustan said:
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
 
M

Markus Weihs

Am Sat, 14 Jan 2006 13:24:01 -0800 schrieb Dustan:
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?

Hi!

Fredrik Lundh's ValidateEntry might be what you want.
http://tkinter.unpythonic.net/wiki/ValidateEntry

Regards, Markus
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top