尽管未收集 tkinter 图像但未显示

tkinter image not displaying despite not being collected

以下不会显示任何内容:

def pic(name):
    def p(image=[]): #keep a reference to the image, but only load after creating window
        if not image: 
            image.append(PhotoImage("../pic/small/"+name+".png")) 
        return image[0]
    def do(canvas, point, angle, size, fill, outline):
        canvas.create_image(*point, image=p(), tag="visual")
    return do

flame = pic("flame")

flame(canvas, (100, 200), 0, 30, "red", "blue")

第二次调用flame,p还记得它的形象。没有异常发生,但图像没有显示。

但是:

_pic2 = PhotoImage(file="../pic/small/flame.png")
canvas.create_image(300, 200, image=_pic2)

有效

(我知道有一些未使用的参数,但 pic 需要与需要它们的其他函数相同的签名

def do(canvas, point, *_):

会一样好)

(pic, flame, _pic2, canvas) 是全局的

问题似乎根本不是图像被垃圾收集的问题。您只是缺少 file 参数名称,因此该路径被用作图像的 "name"。

使用 PhotoImage(file="../pic/small/"+name+".png") 应该可以解决这个问题。

但是,说到垃圾回收,您实际上并不需要带有列表参数的内部 p 函数。这是您可以将 PhotoImage 定义为函数中的局部变量的罕见情况之一,因为即使在 pic 函数之后,它仍将保留在 do 函数的范围内已经退出,因此不会被垃圾回收。

def pic(name):
    img = PhotoImage(file="../pic/small/"+name+".png")
    def do(canvas, point, angle, size, fill, outline):
        canvas.create_image(*point, image=img, tag="visual")
    return do

(它 在收集 flame 时收集,但是,但是您的方法也是如此。但是正如您所说 flame 是全球,这应该不是问题。)