Random_User
Random_User

Reputation: 1

Python tkinter passing variables between classes or frames

I am new OOP and UI development using tkinter. I currently have the following code:

class Snapshot_app(Tk):
    def __init__(self):
        Tk.__init__(self)
        container = Frame(self)
        container.pack(side="top", fill="both", expand=True)
        self.frames = {}
        for F in (StartPage, PageOne,PageTwo):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky=NSEW)

        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

Class PageOne(Frame):
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        Label(self, text="Path to files").grid(row=1,column=0)

        self.fname = Entry(self)
        self.fname.grid(row=1, column=1)
        app.frames[PageTwo].dummy = self.fname.get()
        b = Button(self,text="Open Page 2",command=lambda:app.show_frame(PageTwo)).grid(row=2,column=1)

Class PageTwo(Frame):
    def __init__(self, parent, controller,dummy=None):
        Frame.__init__(self, parent)
        self.data = dummy     
        print(self.data)

app = Snapshot_app()
app.title("Snapshot Tool")
app.geometry("1200x400")
app.mainloop()

In PageTwo class, it gives me an error saying self.data=None. Which means I am unable to pass the dummy information from PageOne to PageTwo. However, if I put a button on PageTwo whose event triggers the printing of self.data, I am able to successfully get the data from PageOne. I would like to however really avoid usign the button. Any pointers and help would be much appreciated!

Upvotes: 0

Views: 1384

Answers (1)

fameman
fameman

Reputation: 3869

The problem is about the creation of the PageTwo instance. Your instantiate Snapshot_app(). The loop starts and instantiates StartPage, followed by PageOne. At this point PageOne.__init__ is being called which sets

app.frames[PageTwo].dummy = self.fname.get()

In my opinion, this shouldn't even work, because PageTwo was not added to app.frames yet, since the loop is till at the PageOne position. If this is the case, you should receive a KeyError: PageTwo. If this is not the case (I don't know, whether you shared the whole code) and if you already instantiated it somewhere else, then it would exist, but after the instantiation of PageOne, the for loop will proceed with PageTwo overriding the whole existing app.frames[PageTwo] entry and instantiating it without a dummy argument, therefore resulting in self.data = dummy being None.

Upvotes: 1

Related Questions