1

以下不会显示任何内容:

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")

我第二次呼唤火焰时,p 仍然记得它的形象。没有异常发生,但图像不显示。

然而:

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

确实有效

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

def do(canvas, point, *_):

会一样好)

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

4

1 回答 1

2

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

使用PhotoImage(file="../pic/small/"+name+".png")应该修复它。

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

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的是全球性的,这应该不是问题。)

于 2017-09-18T09:05:06.290 回答