I have found a very interesting post under the title "TTK Notebook Share Data Between Imported Tabs".
Here is the link: [https://stackoverflow.com/questions/36032712/ttk-notebook-share-data-between-imported-tabs][1]
This is the main application:
I've created as described there and it works. But how can I share data between these two classes?
For example, if I write the following code to the Main Application:
self.hello = "Hello World"
page1 = Page1(self.notebook, self.hello)
page2 = Page2(self.notebook, self.hello)
I get the error message:
page1 = Page1(self.notebook, self.app_data)
TypeError: init() takes 2 positional arguments but 3 were given
I have been working on it for days, but unfortunately I do not understand where the mistake is. I would be very happy if someone would help me here.
This is the main application (main.py):
import tkinter as tk
from tkinter import ttk
from page1 import Page1
from page2 import Page2
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.notebook = ttk.Notebook(self)
self.notebook.pack(fill="both", expand=True)
page1 = Page1(self.notebook)
page2 = Page2(self.notebook)
self.notebook.add(page1, text="Tab 1")
self.notebook.add(page2, text="Tab 2")
self.hello = "Hello World"
page1 = Page1(self.notebook, self.hello)
page2 = Page2(self.notebook, self.hello)
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
This is the page1 "page1.py":
import tkinter as tk
class Page1(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Das ist Tab 1" self.hello)
label.pack(fill ="both", expand=True, padx=20, pady=10)
And thi is page2 "page2.py":
import tkinter as tk
class Page2(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Das ist Tab 2" self.hello)
label.pack(fill ="both", expand=True, padx=20, pady=10)
CodePudding user response:
The error is telling you exactly what is wrong:
page1 = Page1(self.notebook, self.app_data)
TypeError: __init()__ takes 2 positional arguments but 3 were given
As we can see, your Page2.__init__
takes two positional arguments: self
and parent
. When you do Page1(self.notebook, self.app_data)
, self
is automatically passed to __init__
as the first argument. self.notebook
is passed as parent
, and there's no third parameter to accept self.app_data
.
You need to modify __init__
to accept the data parameter:
class Page2(tk.Frame):
def __init__(self, parent, app_data):
tk.Frame.__init__(self, parent)
self.app_data = app_data
Be aware that will cause a different line to fail, because you also call Page2
without that extra argument here:
page1 = Page1(self.notebook)
It's unclear why you're creating page1
twice, but you need to be consistent in how you're creating it.