Search code examples
pythontkintertabswidgetttk

filling individual frames in tkinter notebook Tabs with widgets (after automatic tab generation)


I found a way makeing it easy to automatically generate multiple Tabs with the ttk notebook. As a "solution" to: http://stackoverflow.com/questions/39175898/automatic-multiple-tab-generation-with-tkinter-notebook?noredirect=1#comment65695477_39175898 But now I have a problem to fill the Tabs with individual content namely widgets. What do I need for "???" in the commented out part? I would appreciate it very much if you show me how to solve this.

from tkinter import *
from tkinter import ttk

###
class MyTab(Frame):

    def __init__(self, root, name):
        Frame.__init__(self, root)

        self.root = root
        self.name = name


###
class Application():

    def __init__(self):

        self.tabs = {'ky': 1}

        print(self.tabs['ky'])

        self.root = Tk()
        self.root.minsize(300, 300)

###     Tab generation
        self.notebook = ttk.Notebook(self.root, width=800, height=550)

        tab_names = ["info", "S00", "S01", "S02", "S03", "S04", "S05", "S06", "S07", "S08", "help"]

        for i in range(0, len(tab_names)):
            tab = MyTab(self.notebook, tab_names[i])
            self.notebook.add(tab, text=tab_names[i])

        self.button = Button(self.root, text='next ->', command=self.next_Tab).pack(side=BOTTOM)

###     info Tab Widgets
        #self.btn1 = Button(???, text='Info Button', command=self.next_Tab).pack(side=RIGHT)

###     S00 Tab Widgets
        #self.btn2 = Button(???, text="test_btn")
        #self.btn2.pack()

###     S01 Tab Widgets and so on...

        self.notebook.pack(side=TOP)

    def next_Tab(self):
        print("next Tab -> not yet defined")

    def run(self):
        self.root.mainloop()

###

Application().run()

Solution

  • The rule is quite simple: to place a widget in another widget, you need a reference to the other widget. In your case, the simple thing to do is create a dictionary to hold references to your frames:

    tabs = {}
    for i in range(0, len(tab_names)):
        tab = MyTab(self.notebook, tab_names[i])
        self.notebook.add(tab, text=tab_names[i])
        tabs[tab_names[i]] = tab
    ...
    self.btn1 = Button(tabs["info"], ...)
    

    By the way, you can make your loop more readable (and more "pythonic") by directly iterating over the list of tab names rather than iterating over the index values:

    tabs = {}
    for tab_name in tab_names:
        tab = MyTab(self.notebook, tab_name)
        self.notebook.add(tab, text=tab_name)
        tabs[tab_name] = tab