How to open PIL Image in Tkinter on Canvas

user164814 picture user164814 · Aug 22, 2013 · Viewed 39.1k times · Source

I can't seem to get my PIL Image to work on canvas. Code:

from Tkinter import*
import Image, ImageTk
root = Tk()
root.geometry('1000x1000')
canvas = Canvas(root,width=999,height=999)
canvas.pack()
image = ImageTk.PhotoImage("ball.gif")
imagesprite = canvas.create_image(400,400,image=image)
root.mainloop()

Error:

Traceback (most recent call last):
  File "C:/Users/Mark Malkin/Desktop/3d Graphics Testing/afdds.py", line 7, in <module>
    image = ImageTk.PhotoImage("ball.gif")
  File "C:\Python27\lib\site-packages\PIL\ImageTk.py", line 109, in __init__
    mode = Image.getmodebase(mode)
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 245, in getmodebase
    return ImageMode.getmode(mode).basemode
  File "C:\Python27\lib\site-packages\PIL\ImageMode.py", line 50, in getmode
    return _modes[mode]
KeyError: 'ball.gif'

I need to use PIL images not PhotoImages because I want to resize my images. Please don't suggest switching to Pygame because I want to use Tkinter.

Answer

Brionius picture Brionius · Aug 22, 2013

Try creating a PIL Image first, then using that to create the PhotoImage.

from Tkinter import *
import Image, ImageTk
root = Tk()
root.geometry('1000x1000')
canvas = Canvas(root,width=999,height=999)
canvas.pack()
pilImage = Image.open("ball.gif")
image = ImageTk.PhotoImage(pilImage)
imagesprite = canvas.create_image(400,400,image=image)
root.mainloop()