You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在tkinter中添加logo图片?运行代码后图片不显示该如何解决

问题原因

你遇到的是Tkinter的经典图片引用被垃圾回收问题:
你在StartPage的__init__方法中将处理好的ImageTk.PhotoImage对象赋值给了局部变量,当__init__方法执行完毕后,这些局部变量会被Python的垃圾回收机制自动清理,Tkinter底层不会主动持有图片对象的引用,最终导致标签找不到对应的渲染资源,图片无法显示。

解决方案

只需要将两个图片对象绑定为StartPage的实例属性即可,修改代码中对应部分如下:

# ACWA_Power_logo 处理部分
acwa_power_img = Image.open("ACWA_Power_logo.png")
acwa_power_img = acwa_power_img.resize((150, 80), Image.ANTIALIAS)
# 将图片对象绑定为实例属性,避免被回收
self.acwa_power_img = ImageTk.PhotoImage(acwa_power_img)
acwa_power_label = tk.Label(self, image=self.acwa_power_img)
acwa_power_label.place(x = 0, y = 0)

# hiwpt2 处理部分
hiwpt_img = Image.open("hiwpt2.jpg")
hiwpt_img = hiwpt_img.resize((150, 80), Image.ANTIALIAS)
# 同样绑定为实例属性
self.hiwpt_img = ImageTk.PhotoImage(hiwpt_img)
hipwt_label = tk.Label(self, image=self.hiwpt_img)
hipwt_label.place(x = 646, y =0 )

修改后重新运行程序即可正常显示两张图片。

内容的提问来源于stack exchange,提问作者Losian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 08:57:02