我正在与
Tkinter
合作并使用 pack
来管理 Frame
。如何在视觉上使 Frame
消失而不删除它或使其不可见?我希望下面的 the
框架填充空间,然后,我希望隐藏的 Frame
重新出现,而另一个 Frame
移回原位。让我澄清一下,我尝试了其他答案,但它们不适合我的需要。我使用Python 3.11.7。
如果您使用
pack
,则可以使用 pack_forget
使边框消失。然后您可以再次使用 pack
使其重新出现。您必须确保当您第二次拨打 pack
时将其放回正确的位置。 grid
对此要好得多,因为网格有一种记住小部件如何添加到屏幕的方法。
这是一个使用
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()