简体   繁体   中英

Display image in tkinter

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()

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM