How do I make a Frame in tkinter disappear and reappear without making another Frame?

41 views Asked by At

I'm working with Tkinter and using pack to manage Frame. How can I visually make a Frame disappear without deleting it or making it invisible? I want the Frame underneath to fill the space, and later, I want the hidden Frame to reappear with the other Frame moving back into place. Let me clarify, I tried the other answers, but they don't suit my needs. I use python 3.11.7.

1

There are 1 answers

1
Bryan Oakley On BEST ANSWER

If you're using pack, then you can use pack_forget to make the frame disappear. You can then use pack again to make it reappear. You have to make sure that when you call pack a second time that you put it back in the proper spot. grid is much better for this since grid has a way of remembering how a widget was added to the screen.

Here's an example using pack:

import tkinter as tk

def toggle():
    if top_frame.winfo_viewable():
        top_frame.pack_forget()
    else:
        top_frame.pack(before=bottom_frame, fill="x")

root = tk.Tk()
root.geometry("300x300")

top_frame = tk.Frame(root, background="bisque", height=100)
bottom_frame = tk.Frame(root)
toggle_button = tk.Button(bottom_frame, text="Toggle", command=toggle)

top_frame.pack(side="top", fill="x")
bottom_frame.pack(side="bottom", fill="both", expand=True)
toggle_button.pack(side="bottom", padx=20, pady=20)

tk.mainloop()

screenshot with top frame visible

screenshot with top frame hidden