How do I use PIL with Tkinter?

TkinterPythonGUI-Programming

The PIL or Pillow package in Python provides a way to process images in a program. We can open an image, manipulate the image for different use, and can use it to visualize the data as well. In order to use the PIL package in Tkinter, you've to install the Python Pillow library in your environment.

To install Pillow, just type pip install pillow. Once the installation has been successful, you can import the module in your project and use it for further implementation.

Example

In this example, we've displayed an image in the canvas widget using Python Pillow package.

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

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x350")

# Create a canvas widget
canvas=Canvas(win, width=700, height=350)
canvas.pack()

# Load the image
img=ImageTk.PhotoImage(file="opera.jpg")

# Add the image in the canvas
canvas.create_image(350, 200, image=img, anchor="center")

win.mainloop()

Output

If we run the above code, it will display an image in the window.

raja
Published on 05-Aug-2021 14:05:20
Advertisements