在Mac OS下使用Python 2.7中的Tkinter + Pillow(PIL)时,PNG图像不显示

问题描述 投票:2回答:2

我想使用Python's TkinterPillow'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中使用枕头时这是一个固有的问题?提前致谢!

macos python-2.7 tkinter label pillow
2个回答
1
投票

我得到了同样的问题,并由此解决了

photo = ImageTk.PhotoImage(img).convert('RGB')

但是这会掉落alpha层


0
投票

使用它,它对我有用。

photo = PhotoImage(...)

label = Label(image=photo)

label.image = photo # keep a reference!

label.pack()
© www.soinside.com 2019 - 2024. All rights reserved.