Tkinter中如何在不同Frame内正确添加按钮等组件及解决框架收缩问题
Hey there! Let's break down exactly what's causing those frames to contract when you add my_button3 to your red tab:
1. Grid Layout is Overriding Your Fixed Frame Size
Tkinter’s grid layout has a default behavior called grid propagation that you’re hitting here. By default, any frame using grid for its children will automatically resize itself to fit those child widgets—even if you explicitly set a fixed width and height for the frame.
Here’s how it plays out in your code:
- When
my_frame2has no buttons, it sticks to the 500x500 size you set because there’s nothing to trigger the propagation. - As soon as you add
my_button3and place it withgrid(row=1, column=1), grid propagation kicks in.my_frame2shrinks down to the minimum size needed to fit that button, completely ignoring your original dimensions.
2. The Notebook is Resizing to Match the Smaller Frame
Your ttk.Notebook widget bases its overall size on the content of the currently active tab. When my_frame2 shrinks to fit the button, the Notebook resizes to match this smaller frame. Since both of your frames are packed with fill="both", expand=1, they stretch to fill the now-smaller Notebook—making both frames look like they’ve contracted.
Quick Test to Confirm
Want to prove this is the issue? Add this line right after creating my_frame2:
my_frame2.grid_propagate(False)
This turns off grid propagation, forcing my_frame2 to keep your 500x500 size no matter what widgets you add to it. You’ll see the frames stay full-size even with the button present.
内容的提问来源于stack exchange,提问作者DylanHammond2022

