I don't understand where the problem is coming from.

Hello everyone,
I’m having a small problem with my code, and I can’t figure out the cause. I’m trying to reproduce a chess game to learn, and I’m just getting started, but I don’t understand why the image I’m displaying isn’t staying. I’ve tried so many things for several days, but nothing works. I’m desperate…

It would be really great if we could find a solution…

Thanks in advance.

PS: I apologize in advance. I’m French, hence my probably not very good English and my variables in French.

from tkinter import
import tkinter as Tk

fn = Tk.Tk() 
fn.title("échec & Co")
Taille = 80
canvas = Canvas(width=Taille*8,height=Taille*8) #créer un canva de 8 fois la taille des cases en hauteur et en largeur (il y as 8 cases de haut et de large sur un plateau d'échec)
canvas.pack()
echiquier = []

def gen_terrain(echiquier):
    for rangée in range (0,8):
        listeRangée = []
        for colonne in range(0,8):
            if colonne%2 != rangée%2 :
                couleur = 'black'
            else:
                couleur = 'white'
            listeRangée.append(couleur) 
            canvas.create_rectangle(colonne*Taille,rangée*Taille,colonne*Taille+Taille,rangée*Taille+Taille,fill=couleur)
        echiquier.append(listeRangée)
        print(listeRangée)
    print("gen_terrain fin")

def placer_piece(position_cible, piece_a_placer):
    X = (int(list(position_cible)[0]) - 1) * Taille + Taille * 0.5
    Y = (int(list(position_cible)[1]) - 1) * Taille + Taille * 0.5
    Image = Tk.PhotoImage(file="image/Pb.png")
    canvas.create_image(X, Y, image=Image)
    canvas.update()
    print("pion placé")

gen_terrain(echiquier)
placer_piece("11", "Pion")
fn.mainloop()

You’re creating a PhotoImage and passing it to create_image.

However, tkinter doesn’t keep a reference to it. (That’s an idiosyncracy of tkinter.)

The only reference to it is the local variable Image.

When placer_piece returns, Image ceases to exist, and there are no references to the image, so it’s garbage-collected.

The solution is to keep a reference to the image yourself, in a global variable in the case of your code.

Great! thank you very much! it works!
But to better understand, and not make the same mistake again, what is the garbage collector?

The garbage collector disposes of objects that you’re no longer using, freeing up their memory.

For example, you might make a list and use it. When you no longer need it, you don’t have to explicitly tell Python to dispose of it. It’s disposed of automatically.