RayBae RayBae - 1 year ago 94
Python Question

Tkinter changing image live after a given time

I currently have a listbox with the paths of dozens of images, when an element in the listbox is selected the image will be displayed in the middle of the gui.

My third image has 2 different looks to it so i wrote:

#Third image
elif (self.index==3):
start = clock()
self.label.configure(image=self.photo2[1])#first image
if (start>2):
self.label.configure(image=self.photo2[2])#second image

For now when the user clicks the third element it will first display the first image, then if reclicked after two seconds it will display the second image, so that works.

However, what I want is for my third image to automatically change after two seconds without reclicking. Is there a way to update an image live in tkinter or any ideas on what approach I could take?

Answer Source

This is a common pattern. You should use Tk.after to run a function that changes the image then schedules the next change.

def change_image(label, imagelist, nextindex):
    root.after(2000, lambda: change_image(label, imagelist, (nextindex+1) % len(imagelist)))

Then call it once and let it do its thing forever.

root = Tk()
change_image(root.label, root.photo2, 0)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download