0

I would like to display multiple images in tkinter canvas looping through at some fixed interval. It works fine without recursiveness.

Here's my code so far, appreciate any suggestion.

from tkinter import *
from PIL import Image, ImageTk

picNames = [f"{x}.png" for x in 'abcd']  # all pics are having equal shape

w, h = (lambda picNames: Image.open(picNames[0]).size)(picNames)  # (640, 640)
lag = 2000

# make GUI
tk = Tk()
tk.title('chessGUI')

canvas = Canvas(tk, width=w, height=h, highlightthickness=0, borderwidth=0)
canvas.grid()

bg_col = 'gray15'
canvas.create_rectangle(0, 0, w, h, fill=bg_col, outline=bg_col)
canvas.config(cursor='tcross')

# main loop
picNameIterator = (x for x in picNames)


def update_ip():
    global picNameIterator

    try:
        picName = next(picNameIterator)
        img = Image.open(picName).resize((w, h))
        img = ImageTk.PhotoImage(img)

        canvas.create_image(w // 2, h // 2, image=img, anchor=CENTER)

        tk.after(int(lag), update_ip)
        # canvas.delete("all")

    except StopIteration:
        picNameIterator = (x for x in picNames)
        update_ip()


update_ip()
tk.attributes('-topmost', True)  # make canvas always on top window
tk.mainloop()

beta green
  • 113
  • 10
  • You didn't state clearly what your problem is. – acw1668 Dec 23 '21 at 12:53
  • Always keep a global reference to thinter images. – hussic Dec 23 '21 at 12:55
  • Also you can use `itertools.cycle` to create a cycle list instead of normal iterator, then you don't need to use `try/except`. – acw1668 Dec 23 '21 at 12:57
  • @acw1668 problem is I am not able to display multi images recursively – beta green Dec 23 '21 at 13:09
  • @hussic didn't understand, sorry – beta green Dec 23 '21 at 13:10
  • @acw1668 yes, that could be an option, but won't solve the issue here. I will explore to keep canvas intact and use canvas.itemconfigure to change different images. I have done such to change text, not images. – beta green Dec 23 '21 at 13:13
  • I don't understand what *"display multi images recursively"* means actually. As @hussic said, you need to save a reference of the image otherwise you will have the same issue of this [question](https://stackoverflow.com/questions/16424091/why-does-tkinter-image-not-show-up-if-created-in-a-function). – acw1668 Dec 23 '21 at 13:15
  • Thanks for your direction. What I meant is display multiple images one after another. – beta green Dec 23 '21 at 13:16
  • 1
    You code works fine after adding `global img` (to avoid the image being garbage collected) inside `update_ip()`. However it is better to create the canvas image item outside the function and then update its image inside the function. – acw1668 Dec 23 '21 at 13:26
  • Oh yea, thousand thanks Sir! – beta green Dec 23 '21 at 13:31

0 Answers0