2017-09-18 33 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,而是爲了延遲加載圖像直到它可以這樣做(不知道爲什麼這是必要的,但是) –