I’m currently trying to setup a GUI in Tkinter so that I can show a sequence of images (named file01.jpg, file02.jpg, etc. etc.). Currently I’m doing it by creating a Sequence object to manage the list of images that I care about:
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)
And then I’m using a rather simple Tkinter script I found online to generate the window and place an image there:
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()
where nextFrame is defined as:
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()
In my python buffer I see the correct image sequence pop up (‘Next Image is: test02,jpg’, etc.) but the new image never pops up!
Does anyone have any explanation for why the image doesn’t pop up?
Thanks!
nathan lachenmyer
Probably what is happening is that the image is getting destroyed by the garbage collector since the only reference to the image is a local variable.
Try keeping a permanent reference to the image, for example: