2013-03-18 44 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