我想用Python's Tkinter和Pillow's ImageTk在用户界面上显示一个PNG图像.这在Windows操作系统中很好,但在Mac中却失败了。在Mac中,它打开一个与PNG图像大小相对应的空窗口,不显示任何错误。
我看到,如果使用Button定向PNG图像,它可以正常工作,但在使用Label时失败(当然,我需要它来显示使用label)。但是,如果图像为gif格式,则使用Label打开图像是有效的。
这是我的代码:
from Tkinter import *
import urllib, cStringIO
from PIL import Image, ImageTk
root = Tk()
root.geometry("")
file = cStringIO.StringIO(urllib.urlopen('http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png').read())
img = Image.open(file)
photo = ImageTk.PhotoImage(img)
xxx= Label(root, image = photo) # Not working in Mac
# xxx= Button(root, image = photo) # This works in Mac
xxx.grid(row=14, column=0, rowspan = 5)
# img.show() # opens perfectly using 'Preview' application in Mac
root.mainloop()我在Windows上测试了上面的代码,这里一切都很好。我是不是遗漏了什么,或者这是在Mac中使用枕头时固有的问题?提前感谢!
发布于 2016-01-26 10:30:36
我也有同样的问题,通过这个解决了
photo = ImageTk.PhotoImage(img).convert('RGB')
但这会降低阿尔法层
发布于 2019-03-21 18:34:37
用这个,它对我有用。
photo = PhotoImage(...)
label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()https://stackoverflow.com/questions/29708822
复制相似问题