首页 > 解决方案 > 更改 PIL 图像的 alpha 时出错

问题描述

我正在尝试使用PIL.Image包设置图像的 alpha 以及tkinter. 这是我的代码。

background_image = Image.open(file_path + "\\static\\backgroundimage.jpg")
background_image = background_image.putalpha(128)
background_photo = ImageTk.PhotoImage(background_image)
background_label = tkinter.Label(dashboard_page, image=background_photo)
background_label.background_image = background_photo
background_label.place(x=0, y=0, relwidth=1, relheight=1)

错误发生在第二行。background_image = background_image.putalpha(128). 如果我注释掉这一行,程序就可以正常工作并显示图像。但是,如果我取消注释此行,我会收到此错误。AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'. 发生了什么事,我该如何解决?谢谢你。我正在使用 Python 3.4.4。

标签: pythonpython-3.xtkinterpython-imaging-library

解决方案


这里的问题是.putalpha直接更改图像并返回None,而不是新图像。因此,要修复代码,只需替换

background_image = background_image.putalpha(128)

经过

background_image.putalpha(128)

它应该可以工作。


推荐阅读