2

I don't know why this code is not displaying any image when I run it.

from tkinter import *
import os

root = Tk()
images = os.listdir()
i = 0
for images in images:
    if images.endswith(".png"):
        photo = PhotoImage(file=images)
        label = Label(image=photo)
        label.pack()
        print("reached here")
root.mainloop()
9
  • Presumably you are getting "reached here" messages? Commented Aug 24, 2020 at 4:51
  • yes I am getting reached here messages but it is not displaying the image Commented Aug 24, 2020 at 4:53
  • can u tell why it is not displayng the image?? Commented Aug 24, 2020 at 4:55
  • 1
    This could be becuase image is "grabage collected", can you try, label.image=photo to keep a reference and let me know? Commented Aug 24, 2020 at 5:03
  • so what should I do to avoid this Commented Aug 24, 2020 at 5:04

2 Answers 2

2

So basically you need to have PIL installed

pip install PIL

then

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

root = Tk()
images = os.listdir()
imglist = [x for x in images if x.lower().endswith(".jpg")]

for index, image in enumerate(imglist): #looping through the imagelist
    photo_file = Image.open(image) 
    photo_file = photo_file.resize((150, 150),Image.ANTIALIAS) #resizing the image
    photo = ImageTk.PhotoImage(photo_file) #creating an image instance
    label = Label(image=photo)
    label.image = photo
    label.grid(row=0, column=index) #giving different column value over each iteration
    print("reached here with "+image)

root.mainloop()

If you want to use pack() manager, then change

for image in imglist:
    ....... #same code as before but grid() to 
    label.pack()

Do let me know if any errors or doubts

Cheers

Sign up to request clarification or add additional context in comments.

Comments

1

I played a little and got some results. You can refine it:

from tkinter import *
import os

root = Tk()
images = os.listdir()
imglist = [x for x in images if x.lower().endswith(".png")]
i = 0
photolist = []
labellist= []
for image in imglist:
    photo = PhotoImage(file=image)
    photolist.append(photo)
    label = Label(image=photo)
    labellist.append(label)
    label.pack()
    print("reached here with "+image)

root.mainloop()

9 Comments

I actually think labellist is not necessary and why is i=0 used?
Oh so you have tried to use list comprehension...but still it is showing one image not multiple images
@Vasu This might be because your images are bigger sized?
Try saying this to see if the code actually works for index,image in enumerate(imglist): and then change label.grid(row=0,column=index). I could also add an answer with the resize, if you want
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.