垃圾收集器破坏了我的图像,我看不到它

the garbage collector destroy my image and I can't see it

我以前遇到过这个问题,我解决了, the thing is that for another program I used the same method canvas.create_image() and I couldn't see my image. My idea is, that the garbage collector destroy it before I see it on my canvas, but I don't know how to stop this. I saw this,但我不知道如何应用到我的程序中。

但是如果我写canvas.create_rectangle(50, 50, 70, 70),我工作的很好,所以我不明白。我还尝试将我的图像添加到标签而不是将其放入我的 canvas,但我遇到了同样的问题,看不到任何东西。但是我从来没有遇到过执行错误。

这是我的代码:

from tkinter import *

root = Tk()
canvas = Canvas(root, bg="yellow")

dino = canvas.create_image(600, 200, image=PhotoImage(file='running_1.png'))

canvas.pack(fill="both", expand=True)

root.mainloop()

试试这个 -

from tkinter import *

root = Tk()
canvas = Canvas(root, bg="yellow")
running =PhotoImage(file='running_1.png')

dino = canvas.create_image(600, 200, image=running)

canvas.pack(fill="both", expand=True)

root.mainloop()

您的代码不起作用,因为您在 canvas.create_image 中引用了 PhotoImage。您应该为其分配一个变量,然后使用 image=variable