Python Tkinter Basics: An Introduction to Tkinter UI with the Pack Layout

In the Pack layout, widgets are organized in a block-like structure, with each widget placed below the previous one. The widgets are automatically resized to fit the available space, which is similar to how block elements work in HTML. The order in which you pack the widgets also determines their position on the screen, just like how the order of HTML elements in the body determines their position on the page.

To use the pack layout we have to call the pack method, this method accepts various parameters:

  • side: the side argument for Packer specifies where a given widget should be placed within the window (possible values: 'top', 'bottom', 'left', 'right' - 'top' is default)
  • fill: how the widget should fit in the parent window (possible values: 'x', 'y' to fill in the horizontal or vertical direction or 'both' to fill the entire space)
  • expand: true or false, depending on what we would like the widget to do when expanded by its parent
  • padx, pady: padding in pixels in x or y direction (similar to margin in HTML)
  • ipadx, ipady: padding in x or y direction inside the widget
  • anchor: The anchor parameter is used to specify where a widget should be positioned within its allocated space. Possible values are: 'n' (north), 'ne' (northeast), 'e' (east), 'se' (southeast), 's' (south), 'sw' (southwest), 'w' (west), 'nw' (northwest), 'center' (default option)

Example of the pack layout with the side parameter

Depending on the side parameter value, widgets can be placed vertically or horizontally:

import tkinter as tk

root = tk.Tk()

# vertical pack layout
button1 = tk.Button(root, text="Devlabs 1")
button2 = tk.Button(root, text="Devlabs 2")
button3 = tk.Button(root, text="Devlabs 3")
button1.pack(side="top", padx=10, pady=10)
button2.pack(side="top", padx=10, pady=10)
button3.pack(side="top", padx=10, pady=10)

# horizontal pack layout
button4 = tk.Button(root, text="Devlabs 4")
button5 = tk.Button(root, text="Devlabs 5")
button4.pack(side="left", padx=10, pady=10)
button5.pack(side="left", padx=10, pady=10)

root.mainloop()

Pack Layout with Python, use the side parameter

Example of the pack layout with the anchor parameter

Labels aligned with the "anchor" parameter: For the "center" anchor the parameter is not set, since this is the default value.

import tkinter as tk

root = tk.Tk()

labelw = tk.Label(root, text="DEVLABS west", bg="lightblue")
labelc = tk.Label(root, text="DEVLABS center", bg="lightblue")
labele = tk.Label(root, text="DEVLABS east", bg="lightblue")

labelw.pack(side="top", anchor='w')
labelc.pack(side="top")
labele.pack(side="top", anchor='e')

root.mainloop()

Pack Layout with Python, use the anchor parameter