Photo won’t load on canvas

  Kiến thức lập trình

I wrote this code as part of a bigger code but the arrow image won’t show when I run the bigger program. However, if I run just my code (not the other code) it works just fine.

class Rating(tk.Tk):

    def __init__(self):

        tk.Tk.__init__(self)
        self.title("Customer Rating")
        self.state('zoomed')

        # Get screen width and height
        screen_width = self.winfo_screenwidth()
        screen_height = self.winfo_screenheight()

        # Create a canvas to contain the faces and arrow
        self.canvas = tk.Canvas(self, width = screen_width, height = 590)
        self.canvas.grid(row = 0, column = 0, columnspan = 5)
        self.arrow_image = None

        # Create scale from 1 to 5        
        self.scale = tk.Scale(self, from_ = 1, to = 5, tickinterval = 1,
                              bg = "light yellow", troughcolor = "#81A696",
                              orient = tk.HORIZONTAL, cursor = "heart",
                              command = self.moveArrow)
        self.scale.set(3) # Set default value of scale to 3
        self.scale.grid(row = 2, column = 0, columnspan = 5, sticky = "NSEW")

        # Draw the faces
        self.turtle = RawTurtle(self.canvas) # Turtle will draw in the canvas
        self.faces()

        # Add arrow image to the canvas
        self.arrow_png = tk.PhotoImage(file = "arrow.png")
        self.arrow_image = self.canvas.create_image(0, 120, image = self.arrow_png)

this is the error:
Traceback (most recent call last):
File “C:UsersmelinAppDataLocalProgramsPythonPython312Libtkinter_init_.py”, line 1962, in call
return self.func(*args)
^^^^^^^^^^^^^^^^
File “C:UsersmelinOneDriveDesktopDELAILAExampleProgramsmenumenu.py”, line 947, in Order
Rating().mainloop()
^^^^^^^^
File “C:UsersmelinOneDriveDesktopDELAILAExampleProgramsmenumenu.py”, line 1187, in init
self.arrow_image = self.canvas.create_image(0, 120, image = self.arrow_png)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:UsersmelinAppDataLocalProgramsPythonPython312Libtkinter_init_.py”, line 2861, in create_image
return self.create(‘image’, args, kw)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:UsersmelinAppDataLocalProgramsPythonPython312Libtkinter_init
.py”, line 2847, in _create
return self.tk.getint(self.tk.call(
^^^^^^^^^^^^^
_tkinter.TclError: image “pyimage21” doesn’t exist

I’ve tried putting the whole file path instead of just arrow.png, adding a reference to avoid garbage collection, loading the image before putting putting it on the canvas, but none of them work 🙁

New contributor

delaila is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT