1

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.

Callum Osborn
  • 321
  • 4
  • 13
  • 2
    The code in that question is not a good basis if you're just beginning to learn how to use Tkinter. It was never intended to be used by beginners. :-\ – Bryan Oakley Mar 07 '18 at 20:28

1 Answers1

1

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:

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685