Python3.8 Tkinter Button image属性不显示原因及解决方案
本文分析Python3.8中Tkinter Button设置image属性后图片不显示的问题。当图片变量作为局部变量或函数返回值时,可能因垃圾回收机制(GC)导致内存地址失效,引发AttributeError。通过将图片变量保存为实例属性或全局变量可解决此问题,确保图片对象生命周期覆盖按钮显示周期。
问题现象与错误复现
如标题所述,这是一个关于Tkinter按钮图片无法显示的问题。在尝试将按钮的image属性指向变量del_icon时,即使将其声明为全局变量(global),问题依然存在,并会抛出类似“”的异常信息。
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
上述错误由代码1引起。
错误代码分析
代码1示例如下:
#!/bin/env python3
from PIL import ImageTk
import tkinter as tk
...
self.del_button = tk.Button(self.frame, text='DEL', width=20, height=20)
self.del_button.config(image=ImageTk.PhotoImage(resize(os.getcwd() + '/delete.png', 0)))
self.del_button.bind('<Button-1>', self.delete_selected_image)
self.del_button.grid(row=0, column=0, sticky=tk.W)

运行结果显示,删除按钮上的图片未能正常渲染,按钮区域呈现空白状态。
del_button的image属性未显示图片
解决方案与验证
随后尝试将del_button的image指向的变量改为局部变量,具体实现见代码2。
代码2示例如下:
#!/bin/env python3
from PIL import ImageTk
import tkinter as tk
...
self.del_button = tk.Button(self.frame, text='DEL', width=20, height=20)
del_icon = ImageTk.PhotoImage(resize(os.getcwd()+'/delete.png', 0))
self.del_button.config(image=del_icon)
self.del_button.bind('<Button-1>', self.delete_selected_image)
self.del_button.grid(row=0, column=0, sticky=tk.W)

此时,删除按钮上的图片显示恢复正常。
del_button的image属性正常显示图片
相关笔记记录如下:
潜在原因分析
该Bug的具体成因尚不明确,推测可能与Python的垃圾回收机制(GC)有关。image属性需要指向有效的内存地址,而方法返回的临时变量在调用结束后可能被立即回收,导致image指向了无效的内存地址。
resize()函数的实现代码如下:
#!/bin/env python3
from PIL import Image
def resize(path):
image = Image.open(path)
raw_width, raw_height = image.size[0], image.size[1]
min_height = 20
min_width = int(raw_width * min_height / raw_height)
return image.resize((min_width, min_height))
至此,关于Python3.8中Tkinter Button设置image属性不显示的问题已介绍完毕。如需了解更多Python Tkinter按钮相关技巧,请查阅本站往期文章或继续浏览后续内容,感谢支持!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









