Question

please help to fix the script.

the problem is that my script for some reason displays blank buttons. and I need to have in each button corresponding image.

from PIL import Image
import glob, os, tkinter

root = tkinter.Tk()

size = 128, 128

for infile in glob.glob("images/*.gif"):
    Im = Image.open(infile)
    pointerIm = Im.thumbnail(size, Image.ANTIALIAS)
    tkinter.Button(root, image=pointerIm).pack()

root.mainloop()
Was it helpful?

Solution

  • You should pass ImageTk.PhotoImage instead of Image.
  • thumbnail method does not return anything; It modifies image inplace.
  • You need to keep references to PhotoImage object. Otherwise it will be garbage collected.
    • In the following code I append PhotoImage objects to images list to keep reference.

from PIL import Image, ImageTk
import glob, os, tkinter

root = tkinter.Tk()

size = 128, 128

images = []
for infile in glob.glob("images/*.gif"):
    Im = Image.open(infile)
    Im.thumbnail(size, Image.ANTIALIAS)
    photo_image = ImageTk.PhotoImage(Im)
    images.append(photo_image)
    tkinter.Button(root, image=photo_image).pack()

root.mainloop()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top