image slide show using tkinter and ImageTk

Question:

i am trying to make an image slide show but i cant get the ImageTk module to work

import tkinter as tk
from itertools import cycle
from ImageTk import PhotoImage

images = ["ffa1c83.jpg", "ffa4600.jpg", "faa4149.jpg", "f099e64.png"]
photos = cycle(PhotoImage(file=image) for image in images)

def slideShow():
  img = next(photos)
  displayCanvas.config(image=img)
  root.after(50, slideShow) # 0.05 seconds

root = tk.Tk()
root.overrideredirect(True)
width = root.winfo_screenwidth()
height = root.winfo_screenwidth()
root.geometry('%dx%d' % (640, 480))
displayCanvas = tk.Label(root)
displayCanvas.pack()
root.after(10, lambda: slideShow())
root.mainloop()

i am using python 3.7

i get this error:

Traceback (most recent call last):
  File "C:UserscjDesktopcode_stuffslideshowslide show V2SlideShowV2.py", 
line 3, in <module>
    from ImageTk import PhotoImage
ModuleNotFoundError: No module named 'ImageTk'
Asked By: anytarsier67

||

Answers:

ImageTk is part of module PIL/pillow

from PIL import ImageTk

ImageTk.PhotoImage is used instead of standard tkinter.PhotoImage which can’t read .png.

In older versions tkinter.PhotoImage couldn’t read even .jpg and it was working only with .gif.


Minimal code

import tkinter as tk
from itertools import cycle
from PIL import ImageTk

images = ["ffa1c83.jpg", "ffa4600.jpg", "faa4149.jpg", "f099e64.png"]
photos = cycle(ImageTk.PhotoImage(file=image) for image in images)

BTW: Read about bug in PhotoImage which removes image from memory when it is assigned to local variable in function – see Note in doc PhotoImage

Answered By: furas