Python3.8 Tkinter Button image属性不显示原因及解决方案

沈知远
沈知远
发布时间:2026-10-14| 5人浏览过
原创

本文分析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按钮相关技巧,请查阅本站往期文章或继续浏览后续内容,感谢支持!

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。