Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the focus from one Text widget to another

Tags:

python

tkinter

I'm new to Python and I'm trying to create a simple GUI using Tkinter.

So often in many user interfaces, hitting the tab button will change the focus from one Text widget to another. Whenever I'm in a Text widget, tab only indents the text cursor.

Does anyone know if this is configurable?

like image 421
LJM Avatar asked Sep 20 '09 03:09

LJM


1 Answers

This is very easy to do with Tkinter.

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

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

For example:

def focus_next_window(event):
    event.widget.tk_focusNext().focus()
    return("break")

text_widget=Text(...)
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 you want this behavior for all text widgets in an application you can use the bind_class() method instead of bind() to make this binding affect all text widgets.

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

like image 126
Bryan Oakley Avatar answered Sep 24 '22 09:09

Bryan Oakley