Updating tkinter label image sequentially

I am trying to show list of selected images sequentially on a label image, but all the attempts I have skip to the last image. Please help

from tkinter import *
from tkinter.filedialog import askopenfile, askdirectory, askopenfilenames
from PIL import ImageTk, Image


def load_images(window):
    global files
    files = askopenfilenames(parent=window, title="Choose image(s)", filetype=[("Images", "*.Jpg")])
    files = iter(files)
    update_image(window, next(files))


def update_image(window, img):
    image = ImageTk.PhotoImage(Image.open(img))
    label_img.configure(image=image)
    label_img.image = image
    img = next(files)
    if img:
        window.after(2, update_image(window, img))
    else:
        return


if __name__ == "__main__":

    root = Tk()
    menubar = Menu(root)
    file = Menu(menubar, tearoff=0)
    file.add_command(label="Load image(s)", command=lambda:load_images(root))
    file.add_command(label="Exit", command=root.quit)
    menubar.add_cascade(label="File", menu=file)
    root.config(menu=menubar)


    test_image = ImageTk.PhotoImage(image=Image.open("test.jpg"))
    global label_img
    label_img = Label(root, image=test_image, bg="#2D2D2D")
    label_img.pack(fill=X, padx=10)

    root.mainloop()

And this code is throwing the following.

  window.after(2, update_image(window, img))
  File "......./Documents/python/v3/GUI.py", line 21, in update_image
    img = next(files)
   StopIteration

Answer

First the exception is raised by next(files) if there is no more item to be iterated, so using if img: cannot fix the exception. Use try / except.

Second window.after(2, update_image(window, img)) will execute update_image(...) immediately, not after 2ms (do you mean 2 seconds actaully?).

Below is the modified update_image() function:

def update_image(window, img):
    image = ImageTk.PhotoImage(file=img)
    label_img.configure(image=image)
    label_img.image = image
    try:
        img = next(files)
        window.after(2000, update_image, window, img) # used 2000 instead of 2
    except:
        print("no more image")