2017-09-18 32 views
1

以下赢得吨显示任何内容:Tkinter的图像不显示,尽管没有收集

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) 

做工作

(1M知道有一些未使用的参数,但是PIC需要相同的签名需要它们

def do(canvas, point, *_): 

将其他功能同样好)

(pic,flame,_pic2,canvas)are global

+1

AREN你是否错过了'file'关键字参数? 'PhotoImage(file =“...”)''而不是'PhotoImage(“...”)'没有它,路径就是图像的“名称”。 –

回答

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

+0

我其实确实需要内部p函数,不是为了gc,而是为了延迟加载图像直到它可以这样做(不知道为什么这是必要的,但是) –