Tkinter Geometry Manager - The Pack method

April 7, 2018

Harsh Patel

With every creation of a GUI window or frame , there arises a concern for placing the widgets in the appropriate and desired place. To settle this issue , we use the concept of Geometry Manager. Tkinter Geometry Manager provides us with three basic geometry managers pack() , place() and grid().

Prefacing with the pack() method , this method is a bit limited in functionalities. When situation demands that you ought to create the widgets and place them side by side or on top of each other then you notably use this method. This method takes into consideration the geometry size of the window and place the widgets adhered to each other.


Button-creation

The first step is the creation of any widget. We decided to apply the button widget.
We construct the button using tk.Button() and copied it to a variable.
Note: here B is uppercase.
It takes number of parameters, but the most crucial one is the root window specification. Root window simply means the window where you are currently working on , or where you desire to place the same widget. Since we are currently are in the main window , we passed main as parameter , following which we assigned a random name to the button using the text attribute. After creation of widget we straightly move to placing the widget, where the actual use of geometry manager methods sets in.



Pack-method-without-arguments

Window result-without arguments

We make use of the same variable which has been used to create the Button widget , and use the .pack() function to place our widget. On executing the command we will see that the widget has been placed on the top-center of the window.

To make it more flexible while placing the method with pack() , we use the attribute side.
Using this attribute we can specify the sides top ,bottom , left and right.
By default the widgets are placed at the top-center of the window , if none is specified.


Pack-method-with-2 buttons

Window result-with2 buttons placed on left hand side

Here, we decided to create two similar buttons , button1 and button2 and place them side by side. Therefore, we passed the arguments left for pack method of both the widgets.
It is comprehensively noted that, the second button i.e button2 has been placed on the right side of the button1. Although we have placed button2 on the left hand side , why is it that it is placed to the right side of button1? The thing to ponder over is that, in pack widget always takes the relative position with reference to the placed area of previous widget. Which means that once the button1 has been placed on the extreme left corner of the window, the next widget considers the area after button1. This feature of pack usually is used for creating navigation bars.