0

why this code dont work?

import tkinter

class GraphicChessBoard(tkinter.Frame):
    def __init__(self,parent,squaresCountWidth=8,squaresCountHeight=8,squaresSize=64):
        tkinter.Frame.__init__(self, parent)
        
        parent.geometry("500x500")
        self.Canvas = tkinter.Canvas(parent,width = 500,height = 500,borderwidth=3)
        self.Canvas.pack()

        img = tkinter.PhotoImage(file = "king.png")
        self.Canvas.create_image(100,100,image = img)

a = tkinter.Tk()
b = GraphicChessBoard(a)
a.mainloop()

this is just some simple code that shows my problem. main problem is showing images on canvas, when there are rectangles drew on this canvas. i need images to be on top of my canvas

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Add `self.img = img` to the end of your `__init__` method – TheLizzard May 20 '21 at 15:17
  • whaaaaat!?!? why it works? – Kacper Jodłowski May 20 '21 at 15:32
  • As BryanOakley pointed out, this problem is the same as the one [here](https://stackoverflow.com/questions/16424091/why-does-tkinter-image-not-show-up-if-created-in-a-function). Basically if you can't access a variable like `img` after the function is done, python deletes that variable which has the side effect of deleting it in `tkinter`'s world – TheLizzard May 20 '21 at 15:34
  • thanks, now i should delete this question? " This question already has answers here: Why does Tkinter image not show up if created in a function? (3 answers) Your post has been associated with a similar question. If this question doesn’t resolve your question, ask a new one. Closed 42 mins ago." – Kacper Jodłowski May 20 '21 at 15:39
  • It would be a bad idea to delete the question. Happy to have helped – TheLizzard May 20 '21 at 15:41

0 Answers0