如何在 Tkinter 的不同框架内实际添加按钮和其他东西

How to actually add buttons and other stuff within different frames in Tkinter

我正在学习如何使用 tkinter 制作 GUI。似乎有很多关于如何制作新框架的资源,但我似乎找不到任何解释如何在多个框架中实际添加内容而不会遇到问题的内容。

我有一个笔记本,因为我正在使用多个选项卡来查看我正在使用的 2 个不同的框架。第一帧中有 2 个按钮,一个隐藏第二个选项卡,另一个按钮显示第二个选项卡。第二个选项卡内是第二个框架。一切正常,但只要我将任何东西放入第二个框架内,两个框架都会缩小。代码如下:

from tkinter import *

from tkinter import ttk

root = Tk()
root.title('Tabs')
root.geometry("500x500")  

my_notebook = ttk.Notebook(root)
my_notebook.pack(pady=15)

def hide():
    my_notebook.hide(1)
    
def show():
    my_notebook.add(my_frame2, text="Red Tab")

my_frame1= Frame(my_notebook, width=500, height=500, bg="blue")
my_frame2= Frame(my_notebook, width=500, height=500, bg="red")

my_frame1.pack(fill="both", expand=1)
my_frame2.pack(fill="both", expand=1)


my_notebook.add(my_frame1, text="Blue Tab")
my_notebook.add(my_frame2, text="Red Tab")
    

my_button = Button(my_frame1, text="Hide Tab2", command=hide).grid(row=0, column=0)
my_button2 = Button(my_frame1, text="Show Tab2", command=show).grid(row=1, column=1)

my_button3 = Button(my_frame2, text="Random button").grid(row=1, column=1)

root.mainloop()

删除my_button3后,一切看起来都很好。当它在代码中时,一切都会缩小。有谁知道我在做什么导致了这个?

在 tkinter 中,当一个框架没有 children 时,它会占据整个 space 它被初始化的地方。然而,当你向它添加一些 child 小部件时,它只需要 space 来容纳它的 children.

在您的代码中,当您将 my_button3 添加到 my_frame2 时,它会缩小以容纳按钮。

早些时候,当您没有将按钮添加到第二个框架时,即使 my_frame1 不需要整个 space 因为 my_frame2还是空的。 my_frame2决定笔记本的大小

因此,您的问题的直接解决方案是:

my_frame1.grid_propagate(False)

my_frame2.grid_propagate(False)

grid_propagate 是做什么的?

它基本上告诉框架 propagate/not 根据其 children 进行传播。 (真 = 传播 [默认])

类似于grid_propagate,还有pack_propagate。正确的使用方法取决于用于将 children 添加到框架的几何管理器。 (不是用于将框架添加到其 parent 的几何管理器)

但是,通常不建议使用 grid_propagatepack_propagate,因为您正在对 space 管理进行硬编码。 Tkinter 擅长根据其 child 小部件调整 parent 的大小。在大多数情况下,这会使整个 GUI 以正确的比例看起来很好。