开发者

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

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/Framew开发者_运维百科orks/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


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)


ImageTk.PhotoImage has a garbage collection (ref count) bug in it. You must place a reference to the PhotoImage object in either a global variable of a class instance variable (e.g., self.myphoto = ImageTk.PhotoImage(i)).

See this warning:

http://infohost.nmt.edu/tcc/help/pubs/pil/image-tk.html


Even thought you do need to call a Tk window you also need to set the directory so that it can find the image.png.

import os
import Image 
import ImageTk
from Tkinter import Tk

os.chdir('C:/../../') # put file path for the image.

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

window.mainloop()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜