我想使用Python's Tkinter
和Pillow's ImageTk
在用户界面中显示PNG图像。这在Windows操作系统中运行良好,但在Mac OS中失败。在Mac中,它会打开一个与PNG图像大小相对应的空窗口,并且不会显示任何错误。
我看到,如果使用Button指示PNG图像,它可以正常工作但使用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中使用枕头时这是一个固有的问题?提前致谢!
我得到了同样的问题,并由此解决了
photo = ImageTk.PhotoImage(img).convert('RGB')
但是这会掉落alpha层
使用它,它对我有用。
photo = PhotoImage(...)
label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()