2012-03-26 57 views
1

我正在嘗試在Tkinter中設置GUI,以便我可以顯示一系列圖像(名爲file01.jpg,file02.jpg等)。目前,我正在做它通過創建一個序列對象來管理,我在乎的圖像列表:使用PIL/Tkinter分析圖像序列

class Sequence: 
    def __init__(self,filename,extension): 
     self.fileList = [] 
     #takes the current directory 
     listing = os.listdir(os.getcwd()) 
     #and makes a list of all items in that directory that contains the filename and extension 
     for item in listing: 
      if filename and extension in item: 
       self.fileList.append(item) 
     #and then sorts them into order 
     self.fileList.sort() 
     print self.fileList 

    def nextImage(self): 
     #returns a string with the name of the next image 
     return self.fileList.pop(0) 

然後我用一個很簡單的Tkinter腳本我在網上找到產生的窗口,放置圖像有:

window = Tkinter.Tk() 
window.title('Image Analysis!') 
sequence = Sequence('test','jpg') 

image = Image.open("test01.jpg") 
image = image.convert('L') 
imPix = image.load() 
canvas = Tkinter.Canvas(window, width=image.size[0], height=image.size[1]) 
canvas.pack() 
image_tk = ImageTk.PhotoImage(image) 
canvas.create_image(image.size[0]//2, image.size[1]//2, image=image_tk) 
window.bind("<space>", lambda e: nextFrame(sequence_object=sequence,event=e)) 
Tkinter.mainloop() 

其中如nextFrame定義:

def nextFrame(sequence_object,event=None): 
    nextImage = sequence_object.nextImage() 
    print 'Next Image is: ',nextImage 
    image = Image.open(nextImage) 
    image = image.convert('L') 
    imPix = image.load() 
    image_tk = ImageTk.PhotoImage(image) 
    canvas.create_image(image.size[0]//2, image.size[1]//2, image=image_tk) 
    canvas.update() 

以我蟒緩衝器我看到正確的圖像序列彈出( '下一個圖像:test02,JPG' 等),但新的即時通訊年齡永遠不會彈出!

有沒有人有任何解釋爲什麼圖像不會彈出?

謝謝!

彌敦道lachenmyer

回答

1

可能發生的情況是,圖像是越來越被垃圾回收銷燬,因爲在圖像唯一的參考是一個局部變量。

儘量保持永久的參考圖像,例如:

... 
self.image_tk = ImageTk.PhotoImage(image) 
... 
+0

看來你是對的! nextFrame()中的一個簡單的'全局image_tk'修復了它。 – 2012-03-26 23:11:44

+0

@asymptoticdesign:無論你創建一個變量來保存圖像,確保該變量不是本地的。 – 2012-03-26 23:13:44