Cannot display an image in a function tkinter

59 views Asked by At

Here is my code

def new_grille():
  global cc
  global tab
  global tableau

  x = cc[0]
  y = cc[1]


  fenetre = tk.Tk()
  fenetre.title('Gomoku : Coup joueur Blanc')
  fenetre.attributes('-fullscreen', True)
  fenetre.bind('<Escape>', lambda e: fenetre.destroy())
  fenetre.config(bg='#FFFFFF')


  tableau = tk.Canvas(fenetre, width = 1700, height = 1500, bg ="#FFFFFF")
  tableau.pack(side = tk.BOTTOM, pady=100)

  img = Image.open('boutton quitter.png')
  img_quitter = ImageTk.PhotoImage(img)


  boutton_quitter = tk.Button(fenetre, width=45, height=7,image = img_quitter, command=lambda x="": on_closing())
  boutton_quitter.image = img_quitter
  boutton_quitter.place(x=1500, y=100)
  boutton_quitter.pack()

Im trying to display on the 'boutton_quitter' button an image ('boutton_quitter.png) but it raise an error (_tkinter.TclError: image "pyimage13" doesn't exist), ive tried lot of things but nothing worked, pls help me :)

I saw different things, toplevel methods and trying to stock the image in a global function but either i messed up, either it dosnt work

1

There are 1 answers

0
toyota Supra On

You cannot use both layout manager boutton_quitter.place(x=1500, y=100) boutton_quitter.pack(). Use one layout manger to suit your need.

When using fenetre.attributes('-fullscreen', True) Don't set. Layout manager value too high such as place(). The pack() is OK to suit your need.

I comment out that we doesn't need.

Snippet:

import tkinter as tk
from PIL import Image, ImageTk

#cc = 0

def new_grille():
  #global cc
  #global tab
  global tableau


  fenetre = tk.Tk()
  fenetre.title('Gomoku : Coup joueur Blanc')
 # fenetre.attributes('-fullscreen', True)
  fenetre.bind('<Escape>', lambda e: fenetre.destroy())
  fenetre.config(bg='#FFFFFF')


  tableau = tk.Canvas(fenetre, width = 700, height = 500, bg ="#FFFFFF")
  tableau.pack(side = tk.BOTTOM, pady=100)

  img = Image.open('p2.png')
  img_quitter = ImageTk.PhotoImage(img)

  boutton_quitter = tk.Button(fenetre, width=250, height=350,image = img_quitter, command=lambda x="": on_closing())
  boutton_quitter.image = img_quitter
  boutton_quitter.place(x=100, y=100)
  #boutton_quitter.pack()
  fenetre.mainloop()

if __name__ == "__main__":
    new_grille()

Screenshot:

enter image description here