Limitting the Contents of an Entry Widget in Tkinter

Discussion in 'Python' started by Dustan, Jan 14, 2006.

  1. Dustan

    Dustan Guest

    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?
     
    Dustan, Jan 14, 2006
    #1
    1. Advertisements

  2. Dustan

    James Stroud Guest

    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
     
    James Stroud, Jan 14, 2006
    #2
    1. Advertisements

  3. Dustan

    Markus Weihs Guest

    Am Sat, 14 Jan 2006 13:24:01 -0800 schrieb Dustan:
    Hi!

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

    Regards, Markus
     
    Markus Weihs, Jan 15, 2006
    #3
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.