[ACCEPTED]-Change the focus from one Text widget to another-tkinter

Accepted answer
Score: 29

This is very easy to do with Tkinter.

There 22 are a couple of things that have to happen 21 to make this work. First, you need to make 20 sure that the standard behavior doesn't happen. That 19 is, you don't want tab to both insert a 18 tab and move focus to the next widget. By 17 default events are processed by a specific 16 widget prior to where the standard behavior 15 occurs (typically in class bindings). Tk 14 has a simple built-in mechanism to stop 13 events from further processing.

Second, you 12 need to make sure you send focus to the 11 appropriate widget. There is built-in support 10 for determining what the next widget is.

For 9 example:

def focus_next_window(event):

text_widget.bind("<Tab>", focus_next_window)

Important points about this code:

  • The method tk_focusNext() returns the next widget in the keyboard traversal hierarchy.
  • the method focus() sets the focus to that widget
  • returning "break" is critical in that it prevents the class binding from firing. It is this class binding that inserts the tab character, which you don't want.

If 8 you want this behavior for all text widgets 7 in an application you can use the bind_class() method 6 instead of bind() to make this binding affect 5 all text widgets.

You can also have the 4 binding send focus to a very specific widget 3 but I recommend sticking with the default 2 traversal order, then make sure the traversal 1 order is correct.

More Related questions