Python PIL ImageTk.PhotoImage() is giving me a bus error?

Dylan picture Dylan · Jul 5, 2010 · Viewed 14.5k times · Source

So I am running python 2.6 on a macbook pro and trying to write the code in python to display an image from a file in a label on a tkinter gui. The image is called image.png. The program runs without errors when I use this code

i = Image.open("image.png")

but when I do this code (I add one line):

i = Image.open("image.png")
photo = ImageTk.PhotoImage(i)

The program will crash and say "Bus error" in the command line. I don't even know what that means. I would think that PIL is installed correctly, since Image works, but the fact that ImageTk does not work puzzles me. Can anybody tell me what might be causing this Bus error?

EDIT: Well I made a new program to test the error further. Here is the exact script I ran:

import Image
import ImageTk

i = Image.open("image.png")
photo = ImageTk.PhotoImage(i)

Now instead of getting "Bus error", this is my traceback.

Traceback (most recent call last):
  File "imageTest.py", line 5, in <module>
    photo = ImageTk.PhotoImage(i)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/PIL/ImageTk.py", line 113, in __init__
    self.__photo = apply(Tkinter.PhotoImage, (), kw)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 3285, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py", line 3226, in __init__
    raise RuntimeError, 'Too early to create image'
RuntimeError: Too early to create image
Exception AttributeError: "PhotoImage instance has no attribute '_PhotoImage__photo'" in <bound method PhotoImage.__del__ of <ImageTk.PhotoImage instance at 0x3c7a30>> ignored

Answer

Rob Lourens picture Rob Lourens · Jul 6, 2010

I don't know about the Bus Error, but you need to create a Tk window before you can call PhotoImage. This script works for me-

import Image 
import ImageTk
from Tkinter import Tk

window = Tk()
i = Image.open("image.png") 
photo = ImageTk.PhotoImage(i)