Image not showing in Canvas tkinter

Image not showing in Canvas tkinter

Problem Description:

I have a code where I’m using the create_image() method of Canvas, I want to use tags to bind the respective methods but when I run the code the image doesn’t show up on the canvas.

I made a simple code example to show what I mean:

from tkinter import *

class CanvasM(Canvas):
    width = 600
    height = 400

    def __init__(self, master):
        super().__init__(master, width=self.width, height=self.height, bg='black')


            file='images/cat-image-no-background/cat.png', x=320, y=180)

        self.tag_bind('imagec', "<ButtonPress-1>",
        self.tag_bind('imagec', "<ButtonRelease-1>", self.release)
        self.tag_bind('imagec', "<B1-Motion>", self.motion)


    def create_an_image(self, file, x, y):
        img = PhotoImage(file)
            x, y, image=img, tags=('imagec',))

    def press(self, event):
        print(event.x, event.y)

    def release(self, event):
        print(event.x, event.y)

    def motion(self, event):
        print(event.x, event.y)

if __name__ == '__main__':
    root = Tk()

    c = CanvasM(root)


It just looks like an empty canvas:
Empty canvas

Solution – 1

There are two issues in create_an_image():

  • img is a local variable, so it will be garbage collected after exiting the function. So use an instance variable self.img instead.
  • you need to use file option of PhotoImage() to specify the filename of the image
    def create_an_image(self, file, x, y):
        # use instance variable self.img instead of local variable img
        # use file option of PhotoImage
        self.img = PhotoImage(file=file)
        self.create_image(x, y, image=self.img, tags=('imagec',))
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.