2013-03-18 43 views
3

我一直在试图包含图像在我的Tkinter小部件,但似乎没有任何工作。这里是我的代码:Python的Tkinter中的图像问题

from Tkinter import * 
from PIL import Image 

root = Tk() 
image = Image.open('images/myimage.jpg') 
root.image = image 
b = Radiobutton(root, text='Image',image=image,value='I') 
b.pack() 
root.mainloop() 

我得到的错误是: Trac的

eback (most recent call last): 
    File "C:/Users/.../loadimages.py", line 7, in <module> 
    b = Radiobutton(root, text='Image',image=image,value='I') 
    File "C:\Python27\lib\lib-tk\Tkinter.py", line 2714, in __init__ 
    Widget.__init__(self, master, 'radiobutton', cnf, kw) 
    File "C:\Python27\lib\lib-tk\Tkinter.py", line 1974, in __init__ 
    (widgetName, self._w) + extra + self._options(cnf)) 
TclError: image "<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=402x439 at 0x2A6B080>" doesn't exist 

大部分互联网资源的建议保持一个参考图像,以避免垃圾收集器,但我看不出我可以比我在这里做的更多。也有关于有多个Tk实例的建议,但我只有一个。

无论谁帮忙,提前致谢!

回答

6

您需要打开使用PIL将图像转换为PhotoImage

from PIL import Image, ImageTk 

image = Image.open("images/myimage.jpg") 
photoimg = ImageTk.PhotoImage(image) 
b = Radiobutton(root, image=photoimg) 

参见:Photoimage API

+0

,完美的工作!谢谢! – 2013-03-18 01:28:14