Home > Software engineering >  Tkinter grid vs pack manager window shrink
Tkinter grid vs pack manager window shrink

Time:07-26

I have an example code that use the Tkinter grid manager for creating and allocating four squares:

root=tk.Tk()
root.rowconfigure(0,weight=1)
root.rowconfigure(1,weight=1)
root.columnconfigure(0,weight=1)
root.columnconfigure(1,weight=1)
canv1=tk.Canvas(root, bg="blue")
canv2 = tk.Canvas(root, bg="yellow")
canv3 = tk.Canvas(root, bg="red")
canv4 = tk.Canvas(root, bg="green")
canv1.grid(row=0, column=0, sticky="nsew")
canv2.grid(row=0, column=1, sticky="nsew")
canv3.grid(row=1, column=0, sticky="nsew")
canv4.grid(row=1, column=1, sticky="nsew")
root.mainloop()

After the main window is created, the squares are proportionally expanding and shrinking when the window size is changed by mouse dragging. Squares are always changed proportionally whenever the windows change their size by dragging and moving any of its edge or window corners.

I'm trying to get this same effect with pack manager. So I have the code:

root=tk.Tk()
upper=tk.Frame(root)
lower=tk.Frame(root)
canv1=tk.Canvas(upper,bg="blue")
canv2 = tk.Canvas(upper, bg="yellow")
canv3 = tk.Canvas(lower, bg="red")
canv4 = tk.Canvas(lower, bg="green")
canv1.pack(side='left', fill='both', expand=True)
canv2.pack(side='right', fill='both', expand=True)
canv3.pack(side='left', fill='both', expand=True)
canv4.pack(side='left', fill='both', expand=True)
upper.pack(side='top', fill='both', expand=True)
lower.pack(side='bottom', fill='both', expand=True)
root.mainloop()

When the pack manager is used the squares are only expanded proportionally, when the size of window is changed. During the shrinking (by dragging some edge or corner), the squares not change their size proportionally. I would like to ask - is it possible to make the squares shrink proportionally while changing windows size using pack manager?

CodePudding user response:

The packer tries to preserve the original size of the widgets as long as possible. If a widget isn't large enough to fit, it only shrinks the widget that won't fit in its preferred size. Thus, if you shrink the window horizontally, the widgets on the right will shrink so that the size of the widgets on the left are preserved.

I think the only workaround is to give every canvas a preferred size of 1x1. If you do that, and then give your window as a whole a geometry (so that the entire window isn't just a couple pixels in size) you will get the behavior you want.

root.geometry("800x800")
...
canv1 = tk.Canvas(upper,bg="blue", width=1, height=1)
canv2 = tk.Canvas(upper, bg="yellow", width=1, height=1)
canv3 = tk.Canvas(lower, bg="red", width=1, height=1)
canv4 = tk.Canvas(lower, bg="green", width=1, height=1)

For this specific problem, I see no advantage to using pack over grid, since you are in fact creating a grid of widgets.

  • Related