How to display different images using grid function using Tkinter?

Python's Tkinter library provides powerful tools for creating graphical user interfaces. The grid() function is an excellent layout manager for displaying multiple images in an organized grid format. This article demonstrates how to create a simple image gallery using Tkinter's grid geometry manager.

Import Required Libraries

We need tkinter for the GUI and PIL (Pillow) for image handling ?

import tkinter as tk
from PIL import ImageTk, Image
import urllib.request
import io

Create the Main Window

Set up the main application window with appropriate size and title ?

import tkinter as tk
from PIL import ImageTk, Image
import urllib.request
import io

root = tk.Tk()
root.geometry("520x520")
root.title("Image Grid Display")
root.configure(bg="white")

print("Window created successfully")
Window created successfully

Load and Process Images

For this demo, we'll create colored rectangles to simulate images ?

import tkinter as tk
from PIL import ImageTk, Image

# Create the main window
root = tk.Tk()
root.geometry("520x520")
root.title("Image Grid Display")
root.configure(bg="white")

# Create sample images (colored rectangles)
def create_sample_image(color, size=(200, 200)):
    image = Image.new('RGB', size, color)
    return ImageTk.PhotoImage(image)

# Create four sample images with different colors
image1 = create_sample_image('red')
image2 = create_sample_image('blue') 
image3 = create_sample_image('green')
image4 = create_sample_image('orange')

print("Images created successfully")
Images created successfully

Create Image Labels

Labels are containers that can display images in Tkinter ?

import tkinter as tk
from PIL import ImageTk, Image

root = tk.Tk()
root.geometry("520x520")
root.title("Image Grid Display")
root.configure(bg="white")

# Create sample images
def create_sample_image(color, size=(200, 200)):
    image = Image.new('RGB', size, color)
    return ImageTk.PhotoImage(image)

image1 = create_sample_image('red')
image2 = create_sample_image('blue')
image3 = create_sample_image('green')
image4 = create_sample_image('orange')

# Create labels for each image
label1 = tk.Label(root, image=image1, bd=2, relief="solid")
label2 = tk.Label(root, image=image2, bd=2, relief="solid")
label3 = tk.Label(root, image=image3, bd=2, relief="solid")
label4 = tk.Label(root, image=image4, bd=2, relief="solid")

print("Labels created successfully")
Labels created successfully

Arrange Images Using Grid Layout

The grid() function positions widgets in rows and columns with additional padding ?

import tkinter as tk
from PIL import ImageTk, Image

root = tk.Tk()
root.geometry("520x520")
root.title("Image Grid Display")
root.configure(bg="white")

# Create sample images
def create_sample_image(color, size=(200, 200)):
    image = Image.new('RGB', size, color)
    return ImageTk.PhotoImage(image)

image1 = create_sample_image('red')
image2 = create_sample_image('blue')
image3 = create_sample_image('green')
image4 = create_sample_image('orange')

# Create and position labels using grid
label1 = tk.Label(root, image=image1, bd=2, relief="solid")
label1.grid(row=0, column=0, padx=10, pady=10)

label2 = tk.Label(root, image=image2, bd=2, relief="solid")
label2.grid(row=0, column=1, padx=10, pady=10)

label3 = tk.Label(root, image=image3, bd=2, relief="solid")
label3.grid(row=1, column=0, padx=10, pady=10)

label4 = tk.Label(root, image=image4, bd=2, relief="solid")
label4.grid(row=1, column=1, padx=10, pady=10)

# Add title
title_label = tk.Label(root, text="2×2 Image Grid", font=("Arial", 16, "bold"), bg="white")
title_label.grid(row=2, column=0, columnspan=2, pady=20)

print("Grid layout applied successfully")
print("Close the window to continue...")

root.mainloop()
Grid layout applied successfully
Close the window to continue...

Complete Example with Real Image Loading

Here's a more practical example that can load actual image files ?

import tkinter as tk
from PIL import ImageTk, Image
import os

class ImageGrid:
    def __init__(self, root):
        self.root = root
        self.root.geometry("800x600")
        self.root.title("Image Grid Gallery")
        self.root.configure(bg="lightgray")
        
        # Store image references to prevent garbage collection
        self.images = []
        
    def load_image(self, path, size=(180, 180)):
        """Load and resize an image from file path"""
        try:
            if os.path.exists(path):
                image = Image.open(path)
                image = image.resize(size, Image.Resampling.LANCZOS)
                photo = ImageTk.PhotoImage(image)
                self.images.append(photo)  # Keep reference
                return photo
            else:
                # Create placeholder if file doesn't exist
                return self.create_placeholder(size)
        except Exception as e:
            return self.create_placeholder(size)
    
    def create_placeholder(self, size=(180, 180)):
        """Create a placeholder image"""
        image = Image.new('RGB', size, 'lightblue')
        photo = ImageTk.PhotoImage(image)
        self.images.append(photo)
        return photo
    
    def create_grid(self, image_paths):
        """Create grid layout with images"""
        for i, path in enumerate(image_paths):
            row = i // 3  # 3 images per row
            col = i % 3
            
            image = self.load_image(path)
            label = tk.Label(self.root, image=image, bd=3, relief="ridge")
            label.grid(row=row, column=col, padx=15, pady=15)
            
            # Add filename below image
            filename = os.path.basename(path) if os.path.exists(path) else f"Image {i+1}"
            name_label = tk.Label(self.root, text=filename, font=("Arial", 10), bg="lightgray")
            name_label.grid(row=row+1, column=col, pady=(0, 10))

# Example usage
if __name__ == "__main__":
    root = tk.Tk()
    app = ImageGrid(root)
    
    # List of image paths (replace with actual paths)
    image_paths = [
        "image1.jpg", "image2.jpg", "image3.jpg",
        "image4.jpg", "image5.jpg", "image6.jpg"
    ]
    
    app.create_grid(image_paths)
    root.mainloop()

Grid Parameters

The grid() function accepts several useful parameters ?

Parameter Description Example
row Row position (starts from 0) row=1
column Column position (starts from 0) column=2
padx Horizontal padding padx=10
pady Vertical padding pady=5
columnspan Span multiple columns columnspan=2
sticky Widget alignment sticky="nsew"

Conclusion

The grid() function provides an efficient way to organize images in a structured layout. Use PIL for image processing and always keep references to PhotoImage objects to prevent garbage collection. This approach works well for photo galleries, dashboards, and any application requiring organized image display.

Updated on: 2026-04-02T17:23:55+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements