Using the Grid Layout Manager in Tkinter

Laying out widgets with the Grid layout manager

Tkinter Tutorial Getting started with TKinter

Heads up! You've already completed this tutorial.

In this tutorial you are going to take a more detailed look at understanding how to arrange widgets with Tkinter's grid layout manager.

In previous tutorials we talked about designing your UI layout. If you are interested, check out:

So for this post, I really want to just jump right in and help you to see more examples of designing UIs with Tkinter.

Grid Layout Manager

I personally think that using the grid layout manager is the easiest manager out of the three managers that Tkinter offers. The reason is because it works similar to a matrix, with rows and columns. The upper left-most corner has row value 0 and column value 0. So moving around the grid and arranging widgets is quite simple. If you want to place widgets in a horizontal row, then the row value stays the same and the column value increases by 1 for each widget. It is similar if you want to move down a column, with the column value staying the same and the row value increasing. Check out the image below for a visual example.

Graph showing how the grid layout manager works in Tkinter. How the grid layout manager works in Tkinter.

Notice above how each widget can be positioned within "cells" by specifying their row and column values. Widgets can also span across multiple rows or columns.

Grid Parameters

Now let's look at some of the main parameters that can help you arrange widgets using the grid layout manager.

Create GUI Applications with Python & Qt6 by Martin Fitzpatrick — (PyQt6 Edition) The hands-on guide to making apps with Python — Over 10,000 copies sold!

More info Get the book

  • row, column -- the row and column values for the location of the widget. Both start from 0.
  • columnspan, rowspan -- specifies how many columns or rows a widget will be in. This is very useful to help get the spacing right for your widgets.
  • padx, pady -- the number of pixels surrounding the widget to create padding between other widgets, for horizontal or vertical padding
  • ipadx, ipady -- how many pixels to use for padding inside the widget, also for horizontal or vertical padding
  • sticky -- specifies a value of S, N, E, W, or a combination of them, e.g. NW, NE, SW, or SE. The parameter tells which side of the "cell" the widget will "stick" to . If you use W+E+N+S, then the widget will fill up the "cell". Default is to center the widget within the "cell".

Simple Example Using Grid

The following is just a simple example to see how to set up our window and use grid(). In the following GUI, we combine LabelCheckbutton, and Button widgets to survey which of the colors people like.

Example Tkinter UI using grid with Survey that asks which colors you like. Example Tkinter UI using grid with Survey that asks which colors you like.

Let's see what the code looks like:

python
from tkinter import *

root = Tk()
root.title("Practice with Grid")
root.geometry("210x180")  # set starting size of window

def display_checked():
    '''check if the checkbuttons have been toggled, and display
    a value of '1' if they are checked, '0' if not checked'''
    red = red_var.get()
    yellow = yellow_var.get()
    green = green_var.get()
    blue = blue_var.get()

    print("red: {}\nyellow:{}\ngreen: {}\nblue: {}".format(
        red, yellow, green, blue))

# Create label
label = Label(root, text="Which colors do you like below?")
label.grid(row=0)

# Create variables and checkbuttons
red_var = IntVar()
Checkbutton(root, width=10, text="red", variable=red_var, bg="red").grid(row=1)

yellow_var = IntVar()
Checkbutton(root, width=10, text="yellow", variable=yellow_var, bg="yellow").grid(row=2)

green_var = IntVar()
Checkbutton(root, width=10, text="green", variable=green_var, bg="green").grid(row=3)

blue_var = IntVar()
Checkbutton(root, width=10, text="blue", variable=blue_var, bg="blue").grid(row=4)

# Create Buttons, one to check which colors are checked,
# and another to close the window.
Button(root, text="Tally", command=display_checked).grid(row=5)
Button(root, text="End", command=root.quit).grid(row=6)

root.mainloop()

First we start off by importing Tkinter and setting up the root window in lines 1-5. The display_checked() function is used with the Checkbutton objects to see which boxes have been selected. The get() method checks if the boxes have been selected, and if so, they return the value of '1' for selected. If not, '0'. We create a Label to display our question in line 19. Notice how in line 20 grid() is used to place the label in the window. The row parameter is set to 0, but is not necessary, in this case, for the first widget. This is because the default values for grid() are row=0, column=0. Also, the column is not included parameter because we only have one column in this interface.

Next we set about creating the four Checkbutton widgets for each color from lines 23-30. And finally the last two buttons, "Tally" and "End", are created. The tally Button calls the display_checked()~ function and prints which colors you selected to the terminal. Notice how for each widget therow` value increases by 1 in order to place it in the next row and under the previous widget.

Output for Tkinter UI, shows which colors the user selected. Output of display_checked function if yellow and green are checked.

Let's take a look at another UI that is a bit more difficult.

Profile Entry UI With Grid

Whenever you create a new account it is very important to enter your personal information so that the system can keep track of you. For the next GUI, we will focus on using grid to create an interface for the user to enter some of their personal data. The following UI uses Label, Entry, and Menu widgets.

Profile Entry UI using Grid and Tkinter. Includes user image, name, gender, eye color, height and weight entry fields. Profile Entry UI using Grid and Tkinter. Includes user image, name, gender, eye color, height and weight entry fields.

Since this tutorial's focus is to help you understand how to use grid, the widgets in the above window are not completely functional. You could add more functionality by allowing the user to select an image or saving the user's information after they finish entering it.

python
from tkinter import *

root = Tk()
root.title("Profile Entry using Grid")
root.geometry("500x300")  # set starting size of window
root.maxsize(500, 300)  # width x height
root.config(bg="lightgrey")

# Profile picture
image = PhotoImage(file="profile.gif")
small_img = image.subsample(4,4)

img = Label(root, image=small_img)
img.grid(row=0, column=0, rowspan=6, padx=5, pady=5)

# Enter specific information for your profile into the following widgets
enter_info = Label(root, text="Please enter your information: ", bg="lightgrey")
enter_info.grid(row=0, column=1, columnspan=4, padx=5, pady=5)

# Name label and entry widgets
Label(root, text="Name", bg="lightgrey").grid(row=1, column=1, padx=5, pady=5, sticky=E)

name = Entry(root, bd=3)
name.grid(row=1, column=2, padx=5, pady=5)

# Gender label and dropdown widgets
gender = Menubutton(root, text="Gender")
gender.grid(row=2, column=2, padx=5, pady=5, sticky=W)
gender.menu = Menu(gender, tearoff=0)
gender["menu"] = gender.menu

# choices in gender dropdown menu
gender.menu.add_cascade(label="Male")
gender.menu.add_cascade(label="Female")
gender.menu.add_cascade(label="Other")
gender.grid()

# Eyecolor label and entry widgets
Label(root, text="Eye Color", bg="lightgrey").grid(row=3, column=1, padx=5, pady=5, sticky=E)
eyes = Entry(root, bd=3)
eyes.grid(row=3, column=2, padx=5, pady=5)

# Height and Weight labels and entry widgets
Label(root, text="Height", bg="lightgrey").grid(row=4, column=1, padx=5, pady=5, sticky=E)
Label(root, text="inches", bg="lightgrey").grid(row=4, column=3, sticky=W)

height = Entry(root, bd=3)
height.grid(row=4, column=2, padx=5, pady=5)

Label(root, text="Weight", bg="lightgrey").grid(row=5, column=1, padx=5, pady=5, sticky=E)
Label(root, text="lbs", bg="lightgrey").grid(row=5, column=3, sticky=W)

weight = Entry(root, bd=3)
weight.grid(row=5, column=2, padx=5, pady=5)

root.mainloop()

We start again by loading the Tkinter module, creating the root window, and creating a Label widget to hold the profile image of the user. Let's look at line 14 to see how to set up the image in the root window. The image is located in row=0, column=0, but it does not appear to be arranged in the top left-most corner. This is due to the next parameter, rowspan, that allows the widget to spread across multiple rows. This can help to better align widgets. Here rowspan=6 because all of the data entry widgets on the right span across six rows.

In lines 17 and 18, we create a Label widget to let the user know what to do in this window. The enter_info object is still in row=0, but notice how we have moved over one column by setting column equal to 1. This widget also spans four columns using columnspan=4.

I won't go over all the widgets, but instead leave them to you to see how you can use grid to arrange widgets.

Summary

In today's tutorial we took a more detailed look at using the grid layout manager to create UI in Tkinter. First, we looked at a few of the parameters that can help to manipulate the layout of q GUI. Then we built two GUIs to help practice the concepts of layout management with grid.

Over 10,000 developers have bought Create GUI Applications with Python & Qt!
Create GUI Applications with Python & Qt6
Take a look

Downloadable ebook (PDF, ePub) & Complete Source code

Also available from Payhip , Gumroad , Leanpub and Amazon Paperback

[[ discount.discount_pc ]]% OFF for the next [[ discount.duration ]] [[discount.description ]] with the code [[ discount.coupon_code ]]

Purchasing Power Parity

Developers in [[ country ]] get [[ discount.discount_pc ]]% OFF on all books & courses with code [[ discount.coupon_code ]]
Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak

Using the Grid Layout Manager in Tkinter was written by Joshua Willman .