I want to create different tabs in my GUI, and be able to write different codes in each tab, and also be able to transfer the variables between tabs. So I tried to write it in different classes. But my code cannot show the defined labels in the proper tab. I want to show label1
in class tab1
, label2
in class tab2
, and so on.
here is my code:
import tkinter as tk
from tkinter import ttk
class Data:
def __init__(self):
self.n = tk.IntVar()
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.minsize(400, 400)
self.maxsize(400, 400)
my_notebook = ttk.Notebook(self)
my_notebook.pack()
tab_frame1 = tk.Frame(my_notebook, width=400, height=400)
tab_frame1.pack()
tab_frame2 = tk.Frame(my_notebook, width=400, height=400)
tab_frame2.pack()
tab_frame3 = tk.Frame(my_notebook, width=400, height=400)
tab_frame3.pack()
my_notebook.add(tab_frame1, text="Tab1")
my_notebook.add(tab_frame2, text="Tab2")
my_notebook.add(tab_frame3, text="Tab3")
self.data = Data()
self.frames = {}
for F in (tab1, tab2, tab3):
frame1 = F(tab_frame1, self.data)
self.frames[F] = frame1
frame1.pack()
class tab1(tk.Frame):
def __init__(self, parent, data):
super().__init__(parent)
self.data = data
label1 = tk.Label(self, text="Tab1")
label1.pack()
class tab2(tk.Frame):
def __init__(self, parent, data):
super().__init__(parent)
self.data = data
label2 = tk.Label(self, text="Tab2")
label2.pack()
class tab3(tk.Frame):
def __init__(self, parent, data):
super().__init__(parent)
self.data = data
label3 = tk.Label(self, text="Tab3")
label3.pack()
app = SampleApp()
app.mainloop()
CodePudding user response:
you can do it in this way:
import tkinter as tk
from tkinter import ttk
class Data:
def __init__(self):
self.n = tk.IntVar()
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.minsize(400, 400)
self.maxsize(400, 400)
self.my_notebook = ttk.Notebook(self)
self.my_notebook.pack(fill="both", expand=True)
self.app_data = {}
lst = [tab1, tab2, tab3]
for N, F in enumerate(lst):
tab = F(self.my_notebook, self.app_data)
self.my_notebook.add(tab, text="Tab" str(N 1))
self.data = Data()
class tab1(tk.Frame):
def __init__(self, parent, data):
super().__init__(parent)
self.data = data
label1 = tk.Label(self, text="Tab1")
label1.pack()
class tab2(tk.Frame):
def __init__(self, parent, data):
super().__init__(parent)
self.data = data
label2 = tk.Label(self, text="Tab2")
label2.pack()
class tab3(tk.Frame):
def __init__(self, parent, data):
super().__init__(parent)
self.data = data
label3 = tk.Label(self, text="Tab3")
label3.pack()
app = SampleApp()
app.mainloop()