ICS 32 Winter 2022
Notes and Examples: Tkinter Layout


Background

When we build applications with graphical user interfaces that are comprised of many widgets — many buttons, text entry fields, canvases, menus, etc. — one of the problems we face is the problem of layout, which is fundamentally the problem of deciding where the various widgets will appear within their window. Tkinter provides tools called layout managers that solve this problem in a few common ways, along with ways to create one's own layout manager if the built-in tools don't do exactly what you need.

Of the built-in layout managers included in Tkinter, the most flexible is one called grid, which should address most straightforward GUI layout needs. This code example focuses on the details of how grid works.


The grid layout manager

The grid layout manager arranges widgets by placing each one into one or more cells on an invisible grid. The grid cells themselves are arranged by the layout manager into rows and columns, with the widgets then arranged within the cells. When you create a GUI using the grid layout manager, you specify which widgets will appear in which cells, as well as the rules dictating how the cells' sizes change as the window's size changes, and how the widgets' sizes and positions change as the grid cells' sizes change.

There are a few things to know about a grid-based layout.


A more complex example

In this example, we highlight an example GUI that demonstrates how to control the layout of widgets using Tkinter's grid layout. The image below shows what the GUI looked like when we were done, with yellow gridlines drawn over the GUI so you can see where each grid cell ends and the next one begins.

Layout Example

A few things are evident from the example:


The code

Below is a link to the example layout that is shown above.