Python的Tkinter中的图像问题

时间:2013-03-18 00:59:26

标签: python tkinter

我一直在尝试将图像包含在我的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实例的建议,但我只有一个。

对于任何有帮助的人,提前致谢!

1 个答案:

答案 0 :(得分:9)

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

from PIL import Image, ImageTk

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

另请参阅:Photoimage API

相关问题