简体   繁体   中英

Why can't you use the function 'pack' and the 'grid in the same code

I know you can't use pack and grid together, but why? Why does it raise an error?

_tkinter.TclError: cannot use geometry manager pack inside . which already has slaves managed by grid

The reason is that each one wants to control the geometry of all widgets inside a given container (Frame, Toplevel, etc), and each one will reapply its rules when it detects that a widget it is controlling changes size.

For example, if you start by using pack, pack will add widgets to the window according to its own algorithm. Depending on the size and orientation of the widgets, this may cause the window to grow or shrink and may cause other widgets with the same master to grow or shrink.

Now, if you add a widget using grid , it's going to do the same thing -- it will add widgets using its own algorithm. Like pack , this might cause the window to grow or shrink, or the widget to change size.

Next, because pack is managing some widgets, when it detects that the window has changed size, it will reapply its own algorithm, possibly changing the size or position of some widgets.

Next, because some of the widgets are managed by grid it will detect that they have changed size and it will try to reapply its algorithm. This might cause the window to grow or shrink, or change the size of some widgets.

Next, because some of the widgets are managed by pack it will detect that they have changed size so it will try to reapply its algorithm. This might cause the window to grow or shrink, or change the size of some widgets.

Next, because some of the widgets are managed by grid it will detect that they have changed size so it will try to reapply its algorithm. This might cause the window to grow or shrink, or change the size of some widgets.

Next, because some of the widgets are managed by pack it will detect that they have changed size so it will try to reapply its algorithm. This might cause the window to grow or shrink, or change the size of some widgets.

... and so on until the end of time, or until something causes this cycle to end.

It actually is possible to use both for widgets that share a common parent if you are very careful and know exactly what will happen, but I've never come across a valid reason to do so.

You also absolutely can (and should ) use both pack and grid in an application as a whole. Both have strengths and weaknesses. For example, you might use pack to add a full width toolbar, a full width statusbar, and middle section for the rest of the app. If the rest of the app is a form, it might make sense to use grid for the widgets inside the middle section of the GUI.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM