grid :Layout of the page to place the components in rows and columns

.

Podcast on Tkinter the Python GUI Development

We will keep one Label along with an Entry box.

Understanding row and column


Tkinter Grid layout management by row & columns & aligning in both horizontal & vertical directions

Horizontal placement is done by rows and vertical placement is done by columns.
Tkinter row and column
# Import the tkinter library for creating the GUI
import tkinter as tk

# Create the main window instance
my_w = tk.Tk()

# Set the size of the window to 300x200 pixels
my_w.geometry("300x200")  

# Create a label and place it in row 1, column 1
l1 = tk.Label(my_w, text='row=1,column=1 ')
l1.grid(row=1, column=1) 

# Create a label and place it in row 1, column 2
l2 = tk.Label(my_w, text=' row=1,column=2')
l2.grid(row=1, column=2) 

# Create a label and place it in row 2, column 1
l3 = tk.Label(my_w, text='row=2,column=1 ')
l3.grid(row=2, column=1) 

# Create a label and place it in row 2, column 2
l4 = tk.Label(my_w, text=' row=2,column=2')
l4.grid(row=2, column=2) 

# Run the event loop to display the window
my_w.mainloop()
The top line is row=1 and second line is row=2, similarly first vertical column is column=1 and next vertical column is column=2

anchor: Widget Alignment in Grid 🔝

Anchor option in grid layout
We can use the anchor attribute to customize widget alignment within the grid cell, such as aligning text or widgets to the top-left, bottom-right, or center of the cell.
import tkinter as tk

my_w = tk.Tk() 
my_w.geometry("300x150")  # Adding labels with different anchor points

label1 = tk.Label(
    my_w, 
    text='Top Left', 
    anchor='nw', 
    bg='yellow', 
    height=3, 
    width=15
) 
label1.grid(row=0, column=0, sticky='nsew') 

label2 = tk.Label(
    my_w, 
    text='Bottom Right', 
    anchor='se', 
    bg='yellow', 
    height=3, 
    width=15
) 
label2.grid(row=1, column=1, sticky='nsew') 

my_w.mainloop()
  • anchor helps position text or widgets within the grid cell, offering more fine-grained control over their layout.
  • You can align widgets to the top-left (nw), bottom-right (se), or any other direction using combinations like n, s, e, w.
Key Differences: ( Sticky & Anchor )
  • Sticky: Determines the widget's alignment and stretch within its grid cell.
  • Anchor: Controls the alignment of content inside the widget.
They are often used together to provide fine control over both the widget's placement and the alignment of its content.

sticky option 🔝

If the component size is less than the available grid space, then we can use 'E','W','N','S' to align right left top and bottom.

Check F Name and L Name is aligned to left and right. We can align the components to top and bottom also.
Tkinter grid sticky
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("250x100")  
my_w.title("plus2net.com")  # Adding a title

l1 = tk.Label(my_w,  text='F Name (sticky=\'W\')' ) #added one Label 
l1.grid(row=1,column=1,sticky='W') 

e1 = tk.Entry(my_w,   width=10,bg='yellow') # added one Entry box
e1.grid(row=1,column=2) 

l2 = tk.Label(my_w,  text='L Name (sticky=\'E\')')  # 
l2.grid(row=2,column=1,sticky='E') 

e2 = tk.Entry(my_w,   width=10,bg='yellow') # added one Entry box
e2.grid(row=2,column=2)

l3 = tk.Label(my_w,  text='Add Door No and Street address')   
l3.grid(row=3,column=1,sticky='W') 

e3 = tk.Entry(my_w,   width=10,bg='yellow') # added one Entry box
e3.grid(row=3,column=2)

my_w.mainloop()
The option sticky='NSEW' mean occupy all the available space in all directions.

columnspan option 🔝

Tkinter window grid layout using rowspan and columnspan to manage multiple rows and columns

By default columnspan=1, we can set to different value by increasing it to expand more than one column.
Tkinter grid columnspan
l1 = tk.Label(my_w, text='First', width=20)
l1.grid(row=1,column=1) 
l2 = tk.Label(my_w, text='Second', width=20)
l2.grid(row=1,column=2) 

l3 = tk.Label(my_w, text='Both First and Second, columnspan=2')
l3.grid(row=2,column=1,columnspan=2)

rowspan options 🔝

We can use rowspan=3 to expand to three rows.
Tkinter grid rowspan
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("300x150")  
l1 = tk.Label(my_w, text='First', width=20)
l1.grid(row=1,column=1) 
l2 = tk.Label(my_w, text='Second', width=20)
l2.grid(row=2,column=1) 
l3 = tk.Label(my_w, text='Third', width=20)
l3.grid(row=3,column=1) 

t1 = tk.Text(my_w,  height=3, width=8,bg='yellow') #text box
t1.grid(row=1,column=2,rowspan=3)

my_w.mainloop()

ipadx,ipady,padx,pady options 🔝

Tkinter window grid layout using padx pady and internal padding by using ipadx, ipady

ipadx ipady padx pady
ipadx and ipady adds inner padding or the internal padding of the widget border.
l4=tk.Label(my_w,text='ipadx=50,ipady=50',
	borderwidth=2,relief='ridge')
l4.grid(row=2,column=2,ipadx=50,ipady=50)
padx and pady adds padding from the widget to the grid boarder.
l4=tk.Label(my_w,text='padx=50,pady=50',
	borderwidth=2,relief='ridge')
l4.grid(row=2,column=2,padx=50,pady=50)

grid_size() 🔝

This will return a tuple showing first empty columns and rows . In this example we have used upto row=3 and column=3 so we will get output as (4,4).
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("300x150")  
l1 = tk.Label(my_w, text='First', width=8)
l1.grid(row=1,column=1) 
l2 = tk.Label(my_w, text='Second', width=8)
l2.grid(row=2,column=2) 
l3 = tk.Label(my_w, text='Third', width=8)
l3.grid(row=3,column=3) 

print(my_w.grid_size()) # tuple  columns , rows 

my_w.mainloop()
Output
(4, 4)
You can remove the last element and check the output. We will set the value as column=2 for last element.
l3 = tk.Label(my_w, text='Third', width=8)
l3.grid(row=3,column=2) 
Output
(3, 4)

grid_slaves(row=None, column=None) 🔝

We will get a list of widgets manage by the grid.
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("300x150")  
l1 = tk.Label(my_w, text='First', width=8)
l1.grid(row=1,column=1) 
l2 = tk.Label(my_w, text='Second', width=8)
l2.grid(row=2,column=2) 
l3 = tk.Label(my_w, text='Third', width=8)
l3.grid(row=3,column=2) 

print(my_w.grid_slaves()) 

my_w.mainloop()
Output
[<tkinter.Label object .!label3>, <tkinter.Label object .!label2>,
 <tkinter.Label object .!label>]
We can use row and column number to get the widget.
print(my_w.grid_slaves(2,2)) 
Output
[<tkinter.Label object .!label2>]

grid_remove() 🔝

Remove the widget from the particular grid. Can be added again.
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("300x150")  
l1 = tk.Label(my_w, text='First', width=8)
l1.grid(row=1,column=1) 
l2 = tk.Label(my_w, text='Second', width=8)
l2.grid(row=2,column=2) 
l3 = tk.Label(my_w, text='Third', width=8)
l3.grid(row=3,column=2) 
l3.grid_remove()
my_w.mainloop()
To restore the widget in same location we have to just use grid()
l3.grid()

grid_forget() 🔝

Remove the widget from the particular grid. Can be added again at the new location. We have to specify the location while restoring, by default it takes the next new location.
l3.grid_forget()
To restore at the same location we have to specify the row and column.
l3.grid(row=3,column=2)

Removing after some time delay 🔝

We can use the widget as message box and want to remove it after 300 seconds.
l3.after(3000, lambda: l3.grid_remove() )

Remove all widgets 🔝

for w in my_w.grid_slaves(): # Loop through each row 
    w.grid_forget() # remove the row

Remove all widgets of 2nd row only

for w in my_w.grid_slaves(2):
    w.grid_forget() 
or , any one of these lines will work
#for w in my_w.grid_slaves(2): #  
    #    w.grid_forget()  # remove all elements of 2nd row 
#for w in my_w.grid_slaves(2):w.grid_forget()
[w.grid_forget() for w in my_w.grid_slaves(2)]

Remove all widgets of 2nd column

for w in my_w.grid_slaves(None,2):
    w.grid_forget()

Delete widgets 🔝

Delete widget using destroy()
By using destroy() method we can delete a widget permanently. We can't restore it again.
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("300x150")  

b1=tk.Button(my_w,text='Hide: \n grid_forget()',
      command=lambda:l1.grid_forget())
b1.grid(row=0,column=0,padx=2,pady=10)
b2=tk.Button(my_w,text='Display : \n grid()',
      command=lambda:l1.grid())
b2.grid(row=0,column=1,padx=2,pady=10) 
b3=tk.Button(my_w,text='Destroy : \n destroy()',
      command=lambda:l1.destroy())
b3.grid(row=0,column=2,padx=2)

l1 = tk.Label(my_w, text='Hi Welcome', width=10)
l1.grid(row=1,column=0,pady=10) 
my_w.mainloop()

grid_info() 🔝

All information about the widget layout in the grid.
import tkinter  as tk 
from tkinter import *
my_w = tk.Tk()
my_w.geometry("400x200")  # Size of the window 
my_w.title("www.plus2net.com")  # Adding a title
l1 = tk.Label(my_w, text='row=1,column=1 ')
l1.grid(row=1,column=1,padx=10,pady=10,ipadx=3,ipady=4) 

#dictionary elements(row,column,ipadx,ipday,sticky,rowspan,columnspan)
print(l1.grid_info()) # dictionary all elements value 
print(l1.grid_info()['column'])# 1
print(l1.grid_info()['padx'])  # 10         

my_w.mainloop()  # Keep the window open

Example: Creating a Grid of Buttons Using Loops 🔝

Dynamically creating grid and placing buttons
import tkinter as tk
my_w = tk.Tk() # Main window
my_w.geometry("300x300")

# Create a 5x5 grid of buttons
for i in range(5):
    for j in range(5):
        btn = tk.Button(my_w, text=f"({i},{j})", width=8, height=2)
        btn.grid(row=i, column=j, padx=5, pady=5)

my_w.mainloop()

Explanation:

  • The outer loop iterates over rows, and the inner loop iterates over columns.
  • Each button is labeled with its grid position using `(i, j)` as text.
  • padx and pady add spacing around each button.

Pack Layout in Tkinter place layout Frame rowconfigure() & columnconfigure()
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    29-03-2021

    CAN YOU SEND ME EBOOKS ON TKINTER

    11-03-2023

    En.grid(coumn=0, row=0, columnspan=3, ipadx=4, ipady=8)




    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer