Today i was Trying to Display All .png files in my current Directory In a GUI With Python and Tkinter but The Code Was Not Wroking in a Way That i expected It only Displays The Last Image of the Folder and The Space for Other Images Was Blank.
# Importing Essentials
import os
from tkinter import Tk, Label, PhotoImage
# Initialize Tk root Class
root = Tk()
# Set Default Size of Our Tkinter Window - (WidthxHeight)
root.geometry("200x910")
# Set Minimum Size of Our Window - (Width, Height)
root.minsize(350, 200)
# Add a Label
WelcomeLabel = Label(text="All Images of This Folder")
WelcomeLabel.pack()
# Get All PNG Files in a List name pngFiles
pngFiles = []
for item in os.listdir():
if item.endswith(".png"):
pngFiles.append(item)
# Display All The PNG files to our GUI Screen
for file in pngFiles:
photoLoaded = PhotoImage(file=file)
mainImageLabel = Label(image=photoLoaded)
mainImageLabel.pack()
# Run The MainLoop
root.mainloop()
CodePudding user response:
With the current code you are overwriting your photoLoaded
with every loop.
Instead you have can pack these photoLoaded
in a list.
Additionally working with grids is recommended when working with multiple items.
both things are implemented in the code below:
# Importing Essentials
import os
from tkinter import Tk, Label, PhotoImage
# Initialize Tk root Class
root = Tk()
# Set Default Size of Our Tkinter Window - (WidthxHeight)
root.geometry("200x910")
# Set Minimum Size of Our Window - (Width, Height)
root.minsize(350, 200)
# Add a Label
WelcomeLabel = Label(text="All Images of This Folder")
WelcomeLabel.grid(row=0)
# Get All PNG Files in a List name pngFiles
pngFiles = []
for item in os.listdir():
if item.endswith(".png"):
pngFiles.append(item)
print(pngFiles)
# Display All The PNG files to our GUI Screen
i = 0
pics = []
for file in pngFiles:
pics.append(PhotoImage(file=file))
Label(root, image=pics[i]).grid(row=i 1)
i = 1
# Run The MainLoop
root.mainloop()
CodePudding user response:
In tkinter the images must have references in memory, you cannot overwrite and reuse them, my solution is to make a list using pathlib, and then create the labels
If you display an image inside a function, then make sure to keep reference to the > image object in your Python program, either by storing it in a global variable or > by attaching it to another object.