3

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 ?

3 Answers 3

9

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()
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

I've find and install Pillow but not how tu use it
@MathieuRobert: Use it just like PIL. Same imports, same code.
-1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.