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

Tkinter报错:'PhotoImage'对象无'_last_child_ids'属性求解决

问题根源

你创建true_button时犯了一个关键错误:把PhotoImage对象作为Button的第一个参数(master父组件参数)传入了。tkinter的Button第一个参数必须是窗口/框架这类容器组件(比如你的类实例self),而不是图片对象。这就是触发AttributeError的原因——PhotoImage不是tkinter容器,没有_last_child_ids属性。

修正步骤
  • 修正Button参数写法:把Button(true_image, ...)改成Button(self, image=true_image, ...),明确指定父组件和image关键字参数。
  • 保留图片对象引用:tkinter的PhotoImage(包括PIL的ImageTk.PhotoImage)如果没有持久化引用,会被Python垃圾回收机制清理,导致按钮上的图片不显示。需要把图片对象绑定到类实例(比如self.true_image)或者按钮对象上。
修正后的完整代码示例

原生tkinter PhotoImage版本

# 加载图片并绑定到实例,避免被回收
self.true_image = PhotoImage(file="true.png")
self.true_button = Button(self, image=self.true_image, highlightthickness=0)
self.true_button.grid(row=2, column=8)

self.false_image = PhotoImage(file="false.png")
self.false_button = Button(self, image=self.false_image, highlightthickness=0)
self.false_button.grid(row=2, column=1)

PIL ImageTk版本

from PIL import Image, ImageTk

# 加载图片并绑定到实例
self.im_true = Image.open("true.png")
self.true_image = ImageTk.PhotoImage(self.im_true)
self.true_button = Button(self, image=self.true_image, highlightthickness=0)
self.true_button.grid(row=2, column=8)

self.im_false = Image.open("false.png")
self.false_image = ImageTk.PhotoImage(self.im_false)
self.false_button = Button(self, image=self.false_image, highlightthickness=0)
self.false_button.grid(row=2, column=1)

这样修改后,既解决了参数错误导致的AttributeError,也避免了图片被回收不显示的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 09:25:21