Tkinter批量配置带图片按钮时仅最后一个按钮生效问题
问题原因
Tkinter 不会为控件 image 属性绑定的图片对象主动保留强引用,当 Python 垃圾回收机制检测到图片对象没有其他变量引用时,会自动销毁该图片,导致控件上的图片显示失效。
你当前代码中每次循环都将生成的适配图片赋值给同一个 self.current_image 属性,前几次循环生成的图片对象会被后续赋值覆盖,失去强引用后被回收,只有最后一次赋值的图片保留了有效引用,因此只有最后一个按钮能正常显示图片。
修复方案
为每个按钮对应的图片对象单独保留强引用即可,你可以直接将图片作为按钮对象的自定义属性存储,也可以用独立的字典/列表存储所有图片,修改后代码如下:
self.image_buttons = {} count = 0 # goes by column for y in range(height_divisor): # row for x in range(width_divisor): self.image_buttons[count] = tk.Button(self.preview_frame) self.image_buttons[count].place( relx=0 + (1 / width_divisor * x), rely=0 + (1 / height_divisor * y), relwidth=1 / width_divisor, relheight=1 / height_divisor, anchor="nw", ) # 为每个按钮单独绑定图片属性,保留强引用避免被回收 self.image_buttons[count].tk_image = fit_image( Image.open(names_of_files[count]), self.image_buttons[count], full=True ) self.image_buttons[count].configure(image=self.image_buttons[count].tk_image) count += 1 print(self.image_buttons)
修改后每个图片都有专属的有效引用,不会被垃圾回收机制清理,所有按钮的图片即可正常显示、点击。
内容的提问来源于stack exchange,提问作者Daggerpov
相关产品推荐
相关产品推荐

