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

Tkinter Canvas使用create_image()绑定标签后图片不显示求助

Tkinter Canvas图片不显示的解决方案

你的代码里图片无法显示的核心原因是Tkinter的PhotoImage对象被垃圾回收:在create_an_image方法中,img是局部变量,方法执行完成后这个变量会被销毁,对应的图片资源也会被释放,导致画布上看不到图片。

修改后的代码如下:

from tkinter import *


class CanvasM(Canvas):
    width = 600
    height = 400

    def __init__(self, master):
        super().__init__(master, width=self.width, height=self.height, bg='black')

        self.pack(pady=20)
        # 初始化实例属性用于保存图片引用
        self.img = None
        self.create_an_image(
            file='images/cat-image-no-background/cat.png', x=320, y=180)

        self.tag_bind('imagec', "<ButtonPress-1>", self.press)
        self.tag_bind('imagec', "<ButtonRelease-1>", self.release)
        self.tag_bind('imagec', "<B1-Motion>", self.motion)

    def create_an_image(self, file, x, y):
        # 将图片对象赋值给实例属性,避免被垃圾回收
        self.img = PhotoImage(file)
        self.create_image(
            x, y, image=self.img, tags=('imagec',))

    def press(self, event):
        print(event.x, event.y)

    def release(self, event):
        print(event.x, event.y)

    def motion(self, event):
        print(event.x, event.y)


if __name__ == '__main__':
    root = Tk()
    root.title('Holi')
    root.geometry("800x600")

    c = CanvasM(root)

    root.mainloop()

修改说明

  • 将img从局部变量改为实例属性self.img,让Canvas实例始终持有图片对象的引用,避免被Python垃圾回收机制回收。
  • 额外注意:确保图片路径images/cat-image-no-background/cat.png正确,若路径错误也会导致图片不显示,可以尝试使用绝对路径测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:20:48