Hansong Li
Hansong Li

Reputation: 437

Tkinter: how to show and hide Frame class

So I have something like this:

in the main app class, I have three frame class. And ideally, I would use show_frame to forget all of them and only grid the one I specified.

self.frames = {}

for F in (StartPage, Page1, Page2):
    frame = F(container, self)
    self.frames[F] = frame

self.show_frame(StartPage)


def show_frame(self, cont):
    for f in self.frames:
        f.grid_forget(self)

    frame = self.frames[cont]
    frame.grid(row=0, column = 0, sticky='nsew')

And this is a sample of the Frame class.

class StartPage(tk.Frame):

    def __init__(self, container, parent):

My problem is, it doesn't work as expected. When it boots up, it shows only StartPage, which is good. And when I try to go to Page1, that's fine as well. But after that I can't go back to StartPage. It would just show empty when I try. One thing concerns me is that when calling f.grid_forget(self), the compiler insist that I give it a argument "self", which I don't need to otherwise. I am wondering if that might be the source of problem.

TIA!

Upvotes: 1

Views: 7115

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385980

Your problem is with this loop:

for f in self.frames:
    ...

In the loop, f will be a class, not an instance. Since self.frames is a dictionary with the actual frames being the values, you want to loop over the values:

for f in self.frames.values():
    f.grid_forget()

Upvotes: 3

Related Questions