How to display items in a Tkinter grid
Tkinter is a python GUI module with the standard library to create cross-platform desktop GUI applications. In this answer, we will learn to display items in the grid. The grid is used to display items in the table. We can place items based on the row and column index position in the grid.
Syntax
widget.grid(row="provide row index here", column = "provide column index here")
Let us take a look at an example of this.
Example
In the following example, we will place items in the grid as shown below.
Label 1 | Label 2 |
Label 3 | Label 4 |
#import tkinter module
import tkinter as tk
#create window
window = tk.Tk()
#provide size to window
window.geometry("300x300")
#create labels
label_one = tk.Label(window, text="One",borderwidth=3, relief="solid")
label_two = tk.Label(window, text="Two",borderwidth=3, relief="solid")
label_three = tk.Label(window, text="Three",borderwidth=3, relief="solid")
label_four = tk.Label(window, text="Four",borderwidth=3, relief="solid")
#place labels in grid
label_one.grid(row = 0, column = 0, padx = 2, pady=2)
label_two.grid(row = 0, column = 1, padx = 2, pady=2)
label_three.grid(row = 1, column = 0, padx = 2, pady=2)
label_four.grid(row = 1, column = 1, padx = 2, pady=2)
window.mainloop()Explanation
Line 5: We create the instance of the Tkinter class,
Tk(), and assign it to thewindowvariable.Line 8: We set the size of the window as
300x300px.Lines 11–14: We create four different labels with borders using the
Labelwidget.Lines 17–20: We place the four labels in the grid. Items are placed based on the row and column index that we provide to the grid method. We have also provided horizontal and vertical padding to the labels.
Free Resources