Geometry Management in Tkinter

In this lesson, we will learn to arrange widgets on the GUI using the different geometry managers available in Tkinter.

We'll cover the following

We have seen the different widgets available in Tkinter. Now, let’s understand how and where to put these widgets on the GUI.

The grid() method

The grid manager is the most important geometry manager in Tkinter. The grid() method allows us to arrange the widgets on the GUI based on rows and columns. We consider the GUI as a two-dimensional table, and each cell in this table can hold a widget. We can assign a cell to a widget by specifying the cell’s column and row number.

Let’s see an example of using the grid() method.

import tkinter as tk

window=tk.Tk()
window.title(" My Window ")
window.geometry("600x400")

mylabel = tk.Label(text = "Hello World!")
mylabel.grid(column=0,row=0)

window.mainloop()
Example of using the grid() method

You can run the above code by clicking the “Run” button. Don’t forget to close the window before we move on.

We have created a label in the above code and placed it on the GUI using the grid() method. We have placed the label at the cell with row number 0 and column number 0 at the top-left side of the window. You might already know that we programmers start counting from 0, not from 1.

Now, let’s create another label and place it somewhere else. We can put it in the first column and first row. Run the code below to view the output.

import tkinter as tk

window=tk.Tk()
window.title(" My Window ")
window.geometry("600x400")

mylabel = tk.Label(text = "Hello World!")
mylabel.grid(column=0,row=0)

mylabel2 = tk.Label(text = "Hello World!")
mylabel2.grid(column=1,row=1)


window.mainloop()
Another example of using the `grid()` method

The pack() method

Apart from the grid() method, Tkinter also provides the pack() method for placing widgets on the GUI. The pack() method organizes widgets in horizontal and vertical boxes and is limited to left, right, top, bottom positions.

Let’s see an example. You can run the code below to see the output.

import tkinter as tk

window=tk.Tk()
window.title(" My Window ")
window.geometry("600x400")

mylabel = tk.Label(text = "Hello World!")
mylabel.pack(side=tk.TOP)

window.mainloop()
Example of using the pack() method

Both grid() and pack() are fundamental parts of geometry management in Tkinter. We will implement these concepts later when we create our Tkinter app.