Insert a .jpg in a canvas with tkinter and Python 3.2

18,435

Just to save anyone else viewing this now from hunting around for the bits and pieces (like I just did)

As Martijn Pieters said use Pillow rather than PIL, but the code looks the same

from tkinter import Tk, Canvas
from PIL import ImageTk, Image

root = Tk()

#Create a canvas
canvas = Canvas(root, width=400, height=300)
canvas.pack()

# Load the image file
im = Image.open('test_image.jpg')
# Put the image into a canvas compatible class, and stick in an
# arbitrary variable to the garbage collector doesn't destroy it
canvas.image = ImageTk.PhotoImage(im)
# Add the image to the canvas, and set the anchor to the top left / north west corner
canvas.create_image(0, 0, image=canvas.image, anchor='nw')

root.mainloop()
Share:
18,435
Mathieu Robert
Author by

Mathieu Robert

I'm an iOS and Android developer in France

Updated on June 05, 2022

Comments

  • Mathieu Robert
    Mathieu Robert almost 2 years

    So I want to put a .jpg in a canvas, all i found on internet is to use PIL but i'm using Python 3.2 so PIL doesn't work. What can i do to insert a .jpg in a canvas with Python 3.2 ?