Need help with moving focus using Tkinter

Jeff Epler jepler at unpythonic.net
Thu Dec 5 10:36:04 EST 2002


Most of your question has already been answered.  I think I may have an
answer to this part:

On Thu, Dec 05, 2002 at 08:36:07AM -0500, Richard Kuhns wrote:
> I should also note that the Tab key moves focus just like it should, but
> Shift-Tab doesn't move the focus backwards.

On some versions of RedHat Linux (and maybe other systems running
XFree86) pressing shift-tab actually sends the following event:

    KeyPress event, serial 26, synthetic NO, window 0x3600001,
        root 0x60, subw 0x0, time 4014367840, (1070,-332), root:(1073,614),
        state 0x1, keycode 23 (keysym 0xfe20, ISO_Left_Tab), same_screen YES,
        XLookupString gives 0 characters:  ""


In a Tk (8.2) app, I use the following to correctly bind shift-tab:

    safe_bind all <Key-ISO_Left_Tab> { tkTabToWindow [tk_focusPrev %W] }

(safe_bind is a wrapper around bind which catches and ignores any
"invalid keysym" error, since not all systems where this app runs know
what ISO_Left_Tab is)


Translation to Tkinter should be:

    t.bind_class("all", "<Key-ISO_Left_Tab>", "tkTabToWindow [tk_focusPrev %W]")

plus exception handling.  Unfortunately, tkTabToWindow is considered a
Tk internal command.  It does platform-dependent things (like selecting
the text of an entry when it gets focus) which .focus_set() doesn't do.

You should probably use

    t.bind_class("all", "<Key-ISO_Left_Tab>",
        t.bind_class("all", "<Shift-Key-Tab>))

to copy the binding (if any) of Shift-Key-Tab to ISO_Left_Tab.


In Tk version 8.3, there is a new virtual binding <<PrevWindow>>, and
the Tk startup code makes to make <Key-ISO_Left_Tab> generate
<<PrevWindow>>.  Tk 8.4 probably continues this tradition.  You could
use this code sequence to create the virtual binding:

    t.event_add("<<PrevWindow>>", "<ISO_Left_Tab>")

I hope this information helps you out.

Jeff




More information about the Python-list mailing list