0
votes

Python Tkinter stockant toutes les images du répertoire dans un vecteur

Je veux stocker toutes les images du dossier (il y en a 46) dans un seul vecteur afin de pouvoir y accéder facilement plus tard, où est-ce que je me trompe?

Cela me donne l'erreur suivante: FileNotFoundError: [Errno 2] Aucun fichier ou répertoire de ce type: '01_a.jpg'

import tkinter as tk
import os
from PIL import Image

root = tk.Tk()

tkimages = []

def laodImages():
    for image in os.listdir(os.getcwd() + '\chars'):
        if image.endswith("jpg"):
            im = Image.open(image)
            tkimage = tk.PhotoImage(im)
            tkimages.append(tkimage)


laodImages()
print(tkimages[1].name)


0 commentaires

3 Réponses :


0
votes

Vous devez d'abord ajouter le chemin du répertoire parent.

import os

import tkinter as tk
import os
from PIL import Image

root = tk.Tk()

tkimages = []
path = os.getcwd() + '/chars'

def laodImages():
    for image in os.listdir(path):
        if image.endswith("jpg"):
            im = Image.open(os.path.join(path, image))
            tkimage = tk.PhotoImage(im)
            tkimages.append(tkimage)


3 commentaires

dans 'os.listdir (chemin)' cela me donne "Undefinde variable 'p'" de la couirse j'ai défini le chemin plus tôt comme vous l'avez fait


Vous échappez également 'c' lorsque vous écrivez '\ chars'. Vous voulez probablement écrire «/ chars».


ocne je le fais / chars, pas \ chars il ne donne aucune erreur, mais je ne peux toujours pas imprimer quoi que ce soit comme tkimages [1] ni je ne peux faire image_label = tk.Label(root,image=tkimages[1])



0
votes

Alors j'en ai choisi une autre, pour moi un moyen plus simple de le faire et ça marche (btw: je jumelle l'image avec son nom)

import tkinter as tk
import glob
from PIL import Image, ImageTk

root = tk.Tk()


pairs = []
paths = glob.glob('./chars/*.jpg')


for path in paths:
    string1 = path
    name = string1[11:len(string1) - 4]

    tkimage = ImageTk.PhotoImage(file=path)   

    pair = (tkimage, name)
    pairs.append(pair)

Je sais que ce n'est pas la manière la plus propre mais fait le travail


0 commentaires

0
votes

J'ai fait cela dans mon projet pour enregistrer les images d'un dossier dans une liste et l'afficher à l'aide de tkinter

parking_img_list = []

parking_img_path = '/home/stephen/Desktop/Smart Parking System/Smart Parking UI/UI_Layout/*.png'
parking_path_list = glob.glob(parking_img_path)

for parking_file in parking_path_list:
    path = parking_file
    park_img = ImageTk.PhotoImage(file=path)
    parking_img_list.append(park_img)

print(parking_img_list)
image_number = 1


my_display = Label(image=parking_img_list[0])


0 commentaires