How to resize the background image to window size in Tkinter?


In order to work with images, Python Library provides Pillow or PIL package that enables applications to import images and perform various operations on them.

Let us suppose that we want to resize an image dynamically to its window. In such case, we have to follow these steps −

  • Open the Image in the Tkinter Application.

  • Create a Canvas Widget and use create_image(**options) to place the loaded image in the canvas.

  • Define a function to resize the loaded image.

  • Bind the function with the parent window configuration.


# Import the required libraries
from tkinter import *
from PIL import ImageTk, Image

# Create an instance of Tkinter Frame
win = Tk()

# Set the geometry of Tkinter Frame

# Open the Image File
bg = ImageTk.PhotoImage(file="tutorialspoint.png")

# Create a Canvas
canvas = Canvas(win, width=700, height=3500)
canvas.pack(fill=BOTH, expand=True)

# Add Image inside the Canvas
canvas.create_image(0, 0, image=bg, anchor='nw')

# Function to resize the window
def resize_image(e):
   global image, resized, image2
   # open image to resize it
   image ="tutorialspoint.png")
   # resize the image with width and height of root
   resized = image.resize((e.width, e.height), Image.ANTIALIAS)

   image2 = ImageTk.PhotoImage(resized)
   canvas.create_image(0, 0, image=image2, anchor='nw')

# Bind the function to configure the parent window
win.bind("<Configure>", resize_image)


Running the above code will display a window containing an image which can be dynamically resized.

Published on 26-May-2021 11:51:06