2012-03-26 58 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