In the following code I can access information in a notebook tab, in this case, the flag variable of the tab frame.
This can be useful in several situations; in my case, when I drop one of the tabs.
But it is perhaps easier to exemplify by binding to the NotebookTabChanged
event, like so:
import tkinter as tk
from tkinter import ttk
import random
class FrameA(ttk.Frame):
def __init__(self, parent, flag=0):
ttk.Frame.__init__(self, parent)
self.flag = flag
self.label = ttk.Label(self, text="This is Frame A!\nThe flag is {}".format(self.flag))
self.label.pack()
class FrameB(ttk.Frame):
def __init__(self, parent, flag=1):
ttk.Frame.__init__(self, parent)
self.flag = flag
self.label = ttk.Label(self, text="This is Frame B!\nThe flag is {}".format(self.flag))
self.label.pack()
class App(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.notebook = ttk.Notebook(parent)
self.notebook.bind("<<NotebookTabChanged>>", self.tab_changed)
self.tabs = []
for i in range(6):
frame = random.choice([FrameA, FrameB])
j = random.choice(range(30))
self.tabs.append(frame(self.notebook, flag=j))
self.notebook.add(self.tabs[-1], text="Tab {}".format(i))
self.notebook.pack(expand=True, fill='both')
def tab_changed(self, event):
i = self.notebook.index(self.notebook.select())
print("{}".format(self.tabs[i].flag))
if __name__ == '__main__':
root = tk.Tk()
root.geometry('500x200+300+300')
App(root)
root.mainloop()
It could also be helpful to have access to which class (FrameA
or FrameB
) was used in the definition of the selected tab.
Can that be done?