How to set tab order in tkinter app?

I was looking for a way to set the tab order in the tkinter application that I was working on. Currently, the default order works from top to bottom, but for this you need to use CTRL + Tab .

Is there a way to set up an order and, moreover, change CTRL + Tab to just Tab?

+6
source share
1 answer

The order of the tabs is based on the stacking order, which by default corresponds to the order in which widgets are created. You can adjust the stacking order (and therefore the tab order) using the tkraise (or lift ) and lower methods.

To do this, you need to work without a box without pressing CTRL + Tab . Remember, however, that a tab inserts a literal tab in text widgets, rather than moving focus to another control. This default behavior can be changed, of course.

Here is an example showing how to reorder tabs. When you run the example, clicking a tab in the first entry will take you to the last. Pressing the button again will lead you to the second, then the first, foams, rinse, repeat

Note that the native Tk raise and lower commands, but since raise is a reserved word in Python, it had to be renamed to tkinter.

 import Tkinter as tk class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) e1 = tk.Entry(self) e2 = tk.Entry(self) e3 = tk.Entry(self) e1.insert(0,"1") e2.insert(0,"2") e3.insert(0,"3") e1.pack() e2.pack() e3.pack() # reverse the stacking order to show how # it affects tab order new_order = (e3, e2, e1) for widget in new_order: widget.lift() if __name__ == "__main__": app = SampleApp() app.mainloop() 

Since you mention that you need to do CTRL + Tab , I assume that you are trying to change the focus of changing the tab key from a text widget. Typically, the tab key inserts a literal tab. If you want to change focus, just add a binding to the <Tab> event.

Tkinter has a function that will return the name of the next widget that should receive focus. Unfortunately, for older versions of Tkinter, this feature does not work. However, this is easy to get around. Here are some ways you can add to the code above:

  def _focusNext(self, widget): '''Return the next widget in tab order''' widget = self.tk.call('tk_focusNext', widget._w) if not widget: return None return self.nametowidget(widget.string) def OnTextTab(self, event): '''Move focus to next widget''' widget = event.widget next = self._focusNext(widget) next.focus() return "break" 
+13
source

Source: https://habr.com/ru/post/892720/


All Articles