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
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()
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.
-
-
1@MathieuRobert: Use it just like PIL. Same imports, same code.– Martijn Pieters ♦May 14, 2013 at 10:08
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!