Home > Software engineering >  Image not showing in Canvas tkinter
Image not showing in Canvas tkinter

Time:12-02

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')

        self.pack(pady=20)

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

        self.tag_bind('imagec', "<ButtonPress-1>", self.press)
        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)
        self.create_image(
            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()
    root.title('Holi')
    root.geometry("800x600")

    c = CanvasM(root)

    root.mainloop()

It just looks like an empty canvas: Empty canvas

CodePudding user response:

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',))
  • Related