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

The Grid Layout organizes widgets in a grid structure, with each widget placed in a cell defined by its row and column. It's a powerful layout that allows you to define the exact position and size of each widget.

In order to use the grid layout, we have to place the ui components using the grid method. The grid method can be used with the following parameters:

  • row: The row index of the grid cell where the widget will be placed.
  • column: The column index of the grid cell where the widget will be placed.
  • rowspan: The number of rows that the widget will span (default value is 1).
  • columnspan: The number of columns that the widget will span (default value is 1).
  • ipadx: The amount of internal padding to add to the widget in the X direction.
  • ipady: The amount of internal padding to add to the widget in the Y direction.
  • padx: The amount of external padding to add to the widget in the X direction.
  • pady: The amount of external padding to add to the widget in the Y direction.

There is also the sticky parameter which can be used to specify how to fill the cell if the cell is larger than the widget. This can be a combination of the following values:

  • 'n', 's', 'e', 'w': The widget should stick to the top, bottom, right, or left side of the cell, respectively.
  • 'nw', 'ne', 'sw', 'se': The widget should stick to the top-left, top-right, bottom-left, or bottom-right corner of the cell, respectively.
  • 'ns', 'ew': The widget should expand to fill the entire height or width of the cell, respectively.
  • 'nsew': The widget should expand to fill both the height and width of the cell.

Here's an example of the grid layout with a text input and a submit button in the first row and a multiline label in the second row:


import tkinter as tk

root = tk.Tk()

# Create the text input and submit button in the first row
text_input = tk.Entry(root)
submit_button = tk.Button(root, text="Submit")
text_input.grid(row=0, column=0)
submit_button.grid(row=0, column=1)

# Create the multiline label in the second row
label_text = tk.StringVar()
label_text.set("This is a multiline label.\nIt takes up all available width.")
multiline_label = tk.Label(root, textvariable=label_text, justify="left", anchor="w", wraplength=root.winfo_screenwidth())
multiline_label.grid(row=1, column=0, columnspan=2)

root.mainloop()

Pack Layout with Python, use the side parameter