我正在尝试在Tkinter中设置GUI,以便我可以显示一系列图像(名为file01.jpg,file02.jpg等等)。目前我正在通过创建一个Sequence对象来管理我关心的图像列表:
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()
在我的python缓冲区中,我看到弹出正确的图像序列('Next Image is:test02,jpg'等),但新图像永远不会弹出!
有没有人对图像弹出的原因有任何解释?
谢谢!
nathan lachenmyer
答案 0 :(得分:1)
可能发生的事情是图像被垃圾收集器破坏,因为对图像的唯一引用是局部变量。
尝试保留对图像的永久引用,例如:
...
self.image_tk = ImageTk.PhotoImage(image)
...