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

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


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, Canvasfrom PIL import ImageTk, Imageroot = Tk()#Create a canvascanvas = Canvas(root, width=400, height=300)canvas.pack()# Load the image fileim = 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 itcanvas.image = ImageTk.PhotoImage(im)# Add the image to the canvas, and set the anchor to the top left / north west cornercanvas.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.


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!