【问题标题】:PNG image not showing up when using Tkinter + Pillow (PIL) in Python 2.7 under Mac OS在 Mac OS 下的 Python 2.7 中使用 Tkinter + Pillow (PIL) 时未显示 PNG 图像
【发布时间】:2015-04-17 20:32:57
【问题描述】:

我想使用Python's TkinterPillow's ImageTk 在用户界面中显示一个PNG 图像。这在 Windows 操作系统中运行良好,但在 Mac 操作系统中失败。在 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


    【解决方案1】:

    我遇到了同样的问题,通过这个解决了

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

    但这会删除 alpha 层

    【讨论】:

    • 我想你的意思是ImageTk.PhotoImage(img.convert("RGB")),convert 是PIL.Image 上的一个方法。
    【解决方案2】:

    使用这个,它对我有用。

    photo = PhotoImage(...)
    
    label = Label(image=photo)
    
    label.image = photo # keep a reference!
    
    label.pack()
    

    【讨论】:

    • 谢谢!!这也适用于将图像附加到 Button 控件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多