Search code examples
pythontkinterttk

how to binding function with notebook tabs in python tkinter


I would like to use Return key on keyboard to binding function with all tabs. My question is how to separate the function when I going on the difference tabs.

from tkinter import *
from tkinter import ttk
from tkinter.ttk import Notebook

GUI = Tk()
GUI.geometry('1980x1080')

Tab = Notebook(GUI)
FT1 = Frame(Tab)
FT2 = Frame(Tab)
FT3 = Frame(Tab)
Tab.add(FT1,text = 'first tab')
Tab.add(FT2,text = 'second tab')
Tab.add(FT3,text = 'third tab')
Tab.pack(fill = BOTH, expand = 1)

def Return_button(event = None):
    #####if first tab has focuses:
    #####   print('A')
    #####if second tab has focuses:
    #####   print('B')
    pass

GUI.bind('<Return>', Return_button)
GUI.mainloop()

Final code

def Return_button(event = None):
    name = Tab.select()
    index = Tab.index(name)
    if index == 0 :
        print('A')
    elif index == 1 :
        print('B')

Solution

  • You can use name = Tab.select() to get the name of the frame in selected tab, then use Tab.index(name) to get the index of the selected tab:

    def Return_button(event=None):
        name = Tab.select()
        index = Tab.index(name)
        # or text = Tab.tab(name)["text"] to get the text of the selected tab
        print(f"Tab {index} is selected")