Make multiple images in grid canvas expand with window

I am trying to plot 2 images next to each other using Tkinter. I want to use Grid since I will position 10 images in a grid-like position.

In pack I can do it this way, what is the equivalent of that in the grid?

frame1.pack(fill=BOTH, expand=YES)

Here is my code

from tkinter import ttk, Canvas, BOTH, YES
import tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()
root.title("Widget Examples")

# Frame 1
frame1 = Canvas(root)
frame1.grid(row=0, column=0)
pilImage1 ="testImage.jpg")
image1 = ImageTk.PhotoImage(pilImage1)
frame1.create_image(0, 0, image=image1, anchor="nw")

# Frame 2
frame2 = Canvas(root)
frame2.grid(row=0, column=1)
pilImage2 ="testImage.jpg")
image2 = ImageTk.PhotoImage(pilImage2)
frame2.create_image(0, 0, image=image2, anchor="nw")
# Keep unchanged

1 answer

  • answered 2022-01-25 13:22 Delrius Euphoria

    Here is an example that uses Label to show image and get the click coordinates too. You can also use nested loops to create the grid and place Label with grid geometry manager:

    from tkinter import * # Better to use import tkinter as tk
    from PIL import Image, ImageTk
    root = Tk()
    def click_cord(e):
        print(f'x coodinate of click: {e.x}')
        print(f'y coodinate of click: {e.y}')
    img_path = ['path_to_img1','path_to_img2',...] # List with path of 10 images
    tk_lst = [ImageTk.PhotoImage( for x in img_path] # ImageTk instances
    for i in range(2): # Number of rows
        for j in range(5): # Number of columns
            lbl = Label(root,image=tk_lst[5*i+j])
            lbl.bind('<Button-1>',click_cord) # Bind left click to the label

    If you are wondering what tk_lst[5*i+j] is, it is just a way to index the list, tk_lst, in a nested loop, where the index variables, i and j, cannot be deduced as normal 0,1,2,3,... unless an expression is applied on it. The expression can be generalized as: column_count * current_row_iteration + current_column_iteration

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum