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

Tkinter is a popular library for creating user interfaces with Python. In this tutorial you will learn the usage of 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:

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:

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