Reputation: 321
I have created my own python script following the suggestion of this post, Switch between two frames in tkinter.
I have also followed this post, How to access variables from different classes in tkinter python 3.
However, I want to set or change the value of the shared value in one frame and then access it in another, when I switch between the frames.
class MainApplication(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.app = {
"foo": None
}
self.frames = {}
for F in (PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("PageOne")
def show_frame(self, page_name, **kwargs):
# self.app["foo"] = kwargs.get("bar")
frame = self.frames[page_name]
frame.tkraise()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
button = tk.Button(self, text="Login", command=lambda: self.func())
button.pack()
def func(self):
# self.controller.show_frame("PageTwo", bar="something")
self.controller.show_frame("PageTwo")
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
print(self.controller.app["foo"])
I tried adding arguments to the show_frame() function that allows for switching between frames but the result in PageTwo is still None. I have commented out the lines, to show what I attempted.
Upvotes: 1
Views: 273
Reputation: 385830
It's important to understand that PageTwo.__init__
runs at the very start of the program, before the user has a chance to do anything. If you want to access app
after switching, you're going to have to add code that runs after switching.
The following answer, linked to from where you copied your code, shows you one way to do that:
Upvotes: 1