Python 的 Tkinter 中的图像问题 [英] Problems with Images in Python's Tkinter
本文介绍了Python 的 Tkinter 中的图像问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直试图在我的 Tkinter 小部件中包含图像,但似乎没有任何效果.这是我的代码:
I have been trying to include images in my Tkinter widgets, but nothing seems to work. Here's my code:
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 实例的建议,但我只有一个.
Most internet sources suggest keeping a reference to the image to avoid the garbage collector, but I don't see how I could do that more than what I have here. There are also suggestions regarding having multiple Tk instances, but I only have one.
对谁有帮助,提前致谢!
To whoever helps, thanks in advance!
推荐答案
你需要把你用PIL打开的图片转换成PhotoImage
:
You need to convert the image you open using PIL into a PhotoImage
:
from PIL import Image, ImageTk
image = Image.open("images/myimage.jpg")
photoimg = ImageTk.PhotoImage(image)
b = Radiobutton(root, image=photoimg)
另见:Photoimage API
这篇关于Python 的 Tkinter 中的图像问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文