[Tkinter-discuss] Switching between Entry widgets

Michael Lange klappnase at web.de
Thu Jul 21 10:36:00 CEST 2005


Hi Jay,

can you post some of the code that doesn't work for you,
it's easier to figure out what's going wrong if we see what you
have so far.

On Wed, 20 Jul 2005 21:10:17 -0700
Jay Taneja <jay.taneja at gmail.com> wrote:

> the tkinter application i have written has two entry widgets and two
> buttons. what i would like is for the focus to be on the first entry
> widget, such that i launch the program and can immediately input text
> into the entry box. for some reason, i am unable to get the focus()
> command working for me.
> 
> additionally, the input device i am using to put text in the entry
> boxes ends in a carriage return. as soon as this carriage return is
> received in the first entry box, i would like the focus to go to the
> second entry box. when the second entry box gets a carriage return, i
> would like to issue the callback of the first button widget.
> 
> this all seems to make sense in my head, binding the <Return> keypress
> to switch the focus, but i can't seem to get everything working
> correctly. the program doesn't respond to my bindings and i can't get
> the focus switching to work at all.
> 

Just a shot in the dark: maybe you didn't handle the event bind() passes to the
callback correctly, like this:

    entry1.bind('<Return>', button1.focus)# wrong!

bind() passes the event to focus() and focus() doesn't accept this as argument.
There are basically two ways to work around this:
1 - use a lambda that catches the event:
    
    entry1.bind('<Return>', lambda event : button1.focus())

2 - use an extra method as callback that accepts the event as argument:

    def switch_focus(event):
        button1.focus()
    entry1.bind('<Return>', switch_focus)

The advantage of the second option is especially that you can use the information the event provides, e.g.:

    def switch_focus(event):
        if event.widget == entry1:
            button1.focus()
        elif event.widget == entry2:
            button2.focus()
            button2.invoke()

If the problem lies somewhere else, please post some of your code.

Best regards

Michael



More information about the Tkinter-discuss mailing list