1 - Pillow and manipulation of images on a Tkinter window

1.1- The Pillow library

To process images, Python has a module called Pillow. Pillow is currently a successor fork of the PIL (Python Imaging Library) project. It is designed to provide quick access to the data contained in an image, it is endowed with a magic and powerful power for the processing and manipulation of different image formats files such as PNG, JPEG, GIF, TIFF and BMP

1.2- Installation of the Pillow library

The Pillow library can be installed in a very simple way using the pip utility:

pip install pillow

2- Inserting an image using the Pillow library

Now that the Pillow library is installed, it can be used to insert and manipulate images within a Tkinter window. To do this, just import it and create an image object from a file:

from PIL import Image, ImageTk

# Creating the image object
load = Image.open("Pathto_file_images")

# Creating a photo from the image object
photo = ImageTk.PhotoImage(load)

To understand, we will deal with this on a simple example:

  1. Consider an image named car.png 
  2. Let's put the image in a folder called images 
  3.  Let's create a python file in the same directory as the images folder and put the following code:

Example. of image insertion

from tkinter import *
from PIL import Image, ImageTk

root = Tk()
root.title ("Tkinter window")
root.geometry ("300x200")

# Creation of the image object
load = Image.open ("images / car.png")

# Creation of the photo from the image object
photo = ImageTk.PhotoImage (load)

# Place the image in a label
label_image = Label (root, image = photo)
label_image.place (x = 0, y = 0)
root.mainloop ()

Which displays after execution:

3 - Image resizing

The Pillow library also allows you to resize the image using the thumbnail() method, by specifying the dimension  in pixels:

# - * - coding: utf-8 - * -
# Creation of the image object
load = Image.open ("images / car.png")

# Resize the image
load.thumbnail ((50.50))
Younes Derfoufi
my-courses.net

Leave a Reply