Why is image not showing up

Question:

Tried to display an image on a canvas but it won’t show up

import tkinter

class ROOT():
    def __init__(self,root):
        root.geometry("500x500")
        self.canvas=tkinter.Canvas(root,width=500,height=500,bg="white")
        self.canvas.pack()

        self.photoimage=tkinter.PhotoImage(file="Untitled.png")#test image
        self.image=self.canvas.create_image((0,0),image=self.photoimage,anchor="nw")

def main():
    root=tkinter.Tk()
    ROOT(root)
    root.mainloop()

if __name__=="__main__":main()

I am using python 3.10.4 and have no clue why it isn’t working, can somebody explain why

Also sorry for bad English

Asked By: N25_CT13

||

Answers:

You’re supposed to pass two arguments to create_image, instead of a tuple. Also, you need to keep the variable, instead of letting it be garbage collected:

import tkinter

class ROOT():
    def __init__(self,root):
        root.geometry("500x500")
        self.canvas=tkinter.Canvas(root,width=500,height=500,bg="white")
        self.canvas.pack()

        self.photoimage=tkinter.PhotoImage(file="Untitled.png")#test image
        self.image=self.canvas.create_image(0,0,image=self.photoimage,anchor="nw")

def main():
    root=tkinter.Tk()
    root_class=ROOT(root)
    root.mainloop()

if __name__=="__main__":main()
Answered By: pigrammer
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.