【问题标题】:Problems with Images in Python's TkinterPython 的 Tkinter 中的图像问题
【发布时间】:2013-03-18 00:59:25
【问题描述】:

我一直试图在我的 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()

我得到的错误是: 追踪

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 实例的建议,但我只有一个。

向谁提供帮助,在此先感谢!

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    你需要将你使用PIL打开的图片转换成PhotoImage

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

    另请参阅:Photoimage API

    【讨论】:

      猜你喜欢
      • 2020-10-25
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      • 2020-09-18
      相关资源
      最近更新 更多