Problème pour afficher une image avec tkinter

Résolu
Bonjour, je viens sur ce forum car je suis à court d' idée pour régler mon problème.

J' écris un programme python pour faire un jeu de sept familles en graphique, il faut donc que j' affiche les cartes, dans une fonction pour ne pas le réécrire à chaque fois. Le code marche hors de la fonction mais dedans ça ne marche plus, ça affiche juste la zone du cadre et je ne sais pas du tout pourquoi, alors si vous pouvez m' aider, merci de répondre à ce message je ne sais plus quoi faire !

Donc là ça marche :

from tkinter import *
from PIL import *

root= Tk()
root.geometry("1000x500")
root.config(bg="#000000")
thm="marvel"
mainj1=["carte 1","carte2","carte3","carte4"]
mainj1.sort()
myframe=Frame(root)
myframe.pack()
n=len(mainj1)
m=len(mainj1)
colonne=1
while n!=0:
if m-n==8 or m-n==16:
colonne=1
locals()["image"+str(m-n)]=Image.open(mainj1[m-n][0:2]'.jpg')
locals()["image"+str(m-n)]=locals()["image"+str(m-n)].resize((145, 200))
locals()["pic"+str(m-n)]=ImageTk.PhotoImage(locals()["image"+str(m-n)])
locals()["c"+str(m-n+6)]=Label(myframe,image=locals()["pic"+str(m-n)])
if m-n<8:
locals()["c"+str(m-n+6)].grid(row=1,column=colonne)
colonne+=1
elif m-n<16:
locals()["c"+str(m-n+6)].grid(row=2,column=colonne)
colonne+=1
else:
locals()["c"+str(m-n+6)].grid(row=3,column=colonne)
colonne+=1
n=n-1
root.mainloop()


Mais là non !

from tkinter import *
from PIL import *

def affichage():
n=len(mainj1)
m=len(mainj1)
colonne=1
while n!=0:
if m-n==8 or m-n==16:
colonne=1
locals()["image"+str(m-n)]=Image.open(mainj1[m-n][0:2].jpg)
locals()["image"+str(m-n)]=locals()["image"+str(m-n)].resize((145, 200))
locals()["pic"+str(m-n)]=ImageTk.PhotoImage(locals()["image"+str(m-n)])
locals()["c"+str(m-n+6)]=Label(myframe,image=locals()["pic"+str(m-n)])
if m-n<8:
locals()["c"+str(m-n+6)].grid(row=1,column=colonne)
colonne+=1
elif m-n<16:
locals()["c"+str(m-n+6)].grid(row=2,column=colonne)
colonne+=1
else:
locals()["c"+str(m-n+6)].grid(row=3,column=colonne)
colonne+=1
n=n-1

root= Tk()
root.geometry("1000x500")
root.config(bg="#000000")
thm="marvel"
mainj1=["carte 1","carte2","carte3","carte4"]
mainj1.sort()
myframe=Frame(root)
myframe.pack()
affichage()
root.mainloop()

4 réponses

  1. Bonjour,

    Tu devrais afficher ton code avec les balises de code, mode d'emploi:
    https://codes-sources.commentcamarche.net/faq/11288-les-balises-de-code

    Sinon, moi, pour afficher une image avec Tkinter, je fais ça:
    from tkinter import *
    
    def affichage():
        ''' Affiche une image '''
    
        graph_area.create_image(235,10,anchor = NW, image=leaf)
    
    WIDTH, HEIGHT = 710, 380
    main_win = Tk()
    main_win.configure(background = 'light grey')
    main_win.title('Images')
    main_win.geometry(str(WIDTH)+'x'+str(HEIGHT)+'+300+100')
    
    graph_area = Canvas(main_win,bg='azure',height=HEIGHT-20,width=WIDTH-20)
    graph_area.place(x = 10,y = 10)
    
    leaf = PhotoImage(file='leaf.gif')
    affichage()
    
    main_win.mainloop()
    0
    1. ou avec plusieurs:

      from tkinter import *
      
      def affichage():
          ''' Affiche les images '''
      
          x = 10
          for im in images:
              graph_area.create_image(x,10,anchor = NW, image=im)
              x += 200
      
      images_list = ['leaf.gif', 'stone.gif', 'scissors.gif']
      images = []
      
      WIDTH, HEIGHT = 710, 380
      main_win = Tk()
      main_win.configure(background = 'light grey')
      main_win.title('Images')
      main_win.geometry(str(WIDTH)+'x'+str(HEIGHT)+'+300+100')
      
      graph_area = Canvas(main_win,bg='azure',height=HEIGHT-20,width=WIDTH-20)
      graph_area.place(x = 10,y = 10)
      
      for k in range(len(images_list)): images.append(PhotoImage(file=images_list[k]))
      affichage()
      
      main_win.mainloop()    
      0
  2. J' ai recopié le second code à l' identique en changeant le nom des images et ça me met l'erreur suivante :
    _tkinter.TclError: couldn't recognize data in image file "carte1.jpg"

    Est-ce qu' il faut que je convertisse le format des images pour que ça marche ou est-ce que l' erreur vient d' ailleurs ?
    0
    1. Oui, c'est vrai qu'on affiche que des gif comme ça
      Pour un jpeg, il faut faire ça:

      #ajouter ça au début
      from PIL import Image, ImageTk 


      et ensuite:

      for k in range(len(images_list)):
          image = Image.open(images_list[k]) 
          images.append(ImageTk.PhotoImage(image))
      0
      1. et si tu veux afficher les cartes en lignes et colonnes, pas besoin de trucs comme
                if m-n==8 or m-n==16:
                    colonne=1


        Tu peux utiliser simplement l'opérateur modulo : %

        Exemple avec 6 images à afficher sur 2 lignes et 3 colonnes:

        nb_colonnes = 3
        images = [1,2,3,4,5,6]
        x,y = 10,10
        
        for k in range(len(images)):
            print('affichage image {} à x{} y{}'.format(images[k],x,y))
            x += 20
            if((k%3)+1 == nb_colonnes):
                x=10
                y += 20
        0
    2. Super ça marche, merci beaucoup pour ton aide !
      0