以下内容不会显示任何内容:
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)是全球性的
答案 0 :(得分:2)
问题似乎不是图像被垃圾收集。您只是缺少file
参数名称,因此该路径将用作图像的“名称”。
使用PhotoImage(file="../pic/small/"+name+".png")
应该修复它。
但是,谈到垃圾收集,实际上并不需要带有list参数的内部p
函数。这是极少数情况下您可以将PhotoImage
定义为函数中的局部变量,因为即使在do
函数之后它仍将保留在pic
函数的范围内已退出,因此不会被垃圾收集。
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
是全局的,这不应该是个问题。)