Pythonprovides multiple options for buildingGUI (Graphical User Interface)applications. Among them,Tkinteris one of the most widely used and simplest options. It comes bundled with Python and serves as a standard interface to the Tk GUI toolkit.
However, Tkinter alone does not provide support for advanced image operations such asresizing. To work with images effectively, we use thePillow library, which integrates smoothly with Tkinter and allows image processing tasks like resizing, cropping, rotating, etc.
In this article, we’ll learn how to resize an image in Python using Tkinter and Pillow and display it in a GUI window.
Syntax
Image.resize((width, height), resample=Image.BICUBIC)
Parameters:
- width: required width of the resized image.
- height: required height of the resized image.
Installation
1. Install Pillow
You need to install Pillow (a modern fork of the Python Imaging Library):
pip install pillow
2. Tkinter Installation Note
Windows & macOS: Tkinter comespre-installedwithPython.
Linux (some distros): You may need to install itmanually.
On Ubuntu/Debian:
sudo apt-get install python3-tk
Step-by-Step Implementation
Step 1: Import Required Libraries
Pythonfromtkinterimport*fromPILimportImage,ImageTk
Step 2: Load the Image using Pillow
Python# Read the Imageimage=Image.open("Image File Path")
Step 3: Resize the Image
Pythonresized_image=image.resize((250,200))
Step 4: Display the Image in Tkinter GUI
Python# Convert the resized image for Tkinterimg=ImageTk.PhotoImage(resized_image)# Create a label and assign imagelabel=Label(image=img)label.image=img# Keep a reference to avoid garbage collectionlabel.pack()
Complete Code
Pythonfromtkinterimport*fromPILimportImage,ImageTk# Create the main GUI windowroot=Tk()root.title("Image Resizer")image=Image.open("sample.jpg")# Replace with your image file pathresized_image=image.resize((250,200))img=ImageTk.PhotoImage(resized_image)label=Label(image=img)label.image=img# Required to prevent image from being garbage collectedlabel.pack()# Run the GUI applicationroot.mainloop()
Output:-
250x200Explanation:
- Image.open() loads the image.
- resize() returns a resized copy of the image.
- ImageTk.PhotoImage()converts the image into a format Tkinter understands.
- Label() is used to display the image.
- label.image = img keeps a reference to avoid the image from disappearing.