Mathieu Robert
Mathieu Robert

Reputation: 334

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

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 ?

Upvotes: 3

Views: 19884

Answers (3)

Rich
Rich

Reputation: 343

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()

Upvotes: 9

111111100101110111110
111111100101110111110

Reputation: 63

You just need to create the image in the canvas. Make sure that your image is in the same folder as your code.

    image = PhotoImage (file="image.jpg")
    yourcanvas.canvas.create_image (0, 0, anchor=NW, image=image, tags="bg_img")

That should do it. This will also extend the canvas to the size of the image, just to let you know. Good luck with your project!

Upvotes: -1

Martijn Pieters
Martijn Pieters

Reputation: 1121972

PIL does work on Python 3.2; install Pillow, the friendly PIL fork.

Pillow 2.0.0 adds Python 3 support and includes many bug fixes from around the internet.

Upvotes: 1

Related Questions