Sanmay Kant
Sanmay Kant

Reputation: 159

I have tried everything but my pack_forget does not work in tkinter?

I don't know why but .pack_forget() is not working. Here is the code.

def home():
    home = Frame(root)
    welcome = Label(home, text = 'Welcome!')

    if btn.config('relief')[-1] == 'raised':
        btn.config(relief="sunken")
        home.pack() 
        welcome.pack()
    else:
        btn.config(relief="raised")
        home.pack_forget()
        welcome.pack_forget()
btn = Button(assignmentButtons, text = 'Home', borderwidth = 0, padx = 18, anchor = 'w', activebackground = '#4a4646', activeforeground = '#918787',  relief = RAISED, cursor = 'hand2', command = home)
btn.config(width=25, height=2, bg = '#363333', fg = '#918787')
btn.pack(anchor = 'nw')

Upvotes: 1

Views: 758

Answers (2)

NolantheNerd
NolantheNerd

Reputation: 338

Your issue is one of scope. .pack_forget() is removing the home frame and the welcome label from view. But the widgets that are being forgotten were only just created and never .pack'ed in the first place!

Every time your btn is pressed, a new frame named home and a new label called welcome are created. If btn's relief value is "raised", then these widgets are packed. Otherwise, the freshly created, not yet packed widgets are forgotten (which does nothing because they are not yet visible). You are never actually referring to the already packed widgets. You need to pass a reference to the widgets that were packed in order to remove them.

One way to do this is to generate your tkinter code using a class with home and welcome as attributes of the instantiated class. Then you can reference them with self.home.pack_forget() and self.welcome.pack_forget().

See this link for an example using a class definition.

Upvotes: 1

Matt Binford
Matt Binford

Reputation: 710

I believe the problem you are running into is that you have a function and a TK Frame named the same thing. Try to differentiate them and see if that helps. ie. You have "home" listed as both the function and the Frame attached to root

Upvotes: 0

Related Questions