0

Issue: Why does this code not produce a row of 5 images? Ive tried different combinations of pack, place and grid but I can't resolve the issue. I think the current issue is that the backgrounds of images are overlapping each other but i tried reversing the loop to solve the issue and it changed nothing.

Code:

import base64
try:
    # Python2
    import Tkinter as tk
    from urllib2 import urlopen
except ImportError:
    # Python3
    import tkinter as tk
    from urllib.request import urlopen
root = tk.Tk()
root.title("display a row of images")
root.geometry("%dx%d+%d+%d" % (1000, 600, 0, 0))
images = ["C20KEWS", "ANYT6mV", "b3vwblN", "7Y1MG17", "ouXXEMi"]
for image in images:
    imgbytes = urlopen("http://i.imgur.com/"+image+".gif").read()
    imgb64 = base64.encodestring(imgbytes)
    imageTK = tk.PhotoImage(data=imgb64)
    imageContainer = tk.Frame(root,
        bg="black",
        width=200,
        height=600
    )
    print images.index(image)*200, 0
    imageContainer.place(x=images.index(image)*200, y=0, width=200, height=600)
    imageLabel = tk.Label(imageContainer, image=imageTK, bg='black')
    imageLabel.pack(side=tk.LEFT)
root.mainloop()
nathanhorton
  • 100
  • 1
  • 8

1 Answers1

2

imageTk is overwritten, and garbage collected. They should be there to be displayed.

Save those ImageTk objects to prevent that.

root = tk.Tk()
root.title("display a row of images")
root.geometry("%dx%d+%d+%d" % (1000, 600, 0, 0))
images = ["C20KEWS", "ANYT6mV", "b3vwblN", "7Y1MG17", "ouXXEMi"]
photo_images = []  # <--------
for image in images:
    imgbytes = urlopen("http://i.imgur.com/"+image+".gif").read()
    imgb64 = base64.encodestring(imgbytes)
    imageTK = tk.PhotoImage(data=imgb64)
    photo_images.append(imageTK)  # <-----------
    imageContainer = tk.Frame(root,
        bg="black",
        width=200,
        height=600
    )
    print images.index(image)*200, 0
    imageContainer.place(x=images.index(image)*200, y=0, width=200, height=600)
    imageLabel = tk.Label(imageContainer, image=imageTK, bg='black')
    imageLabel.pack(side=tk.LEFT)
root.mainloop()

enter image description here

falsetru
  • 357,413
  • 63
  • 732
  • 636