[Python] why do I need to specify a variable name for a Canvas Image Object to apper in Tkinter

Discussão em 'Python' iniciado por Stack, Agosto 29, 2025.

  1. Stack

    Stack Membro Participativo

    I created a custom canvas image object class of tkinter. But when I make a instance of it it does not appear in the canvas.

    Here is a simple class to create a Image Object

    import tkinter as tk
    from PIL import Image, ImageTk

    class CreateImage():
    def __init__(self, canvas, image_path, pos=(300, 300)):
    self.canvas = canvas
    self.image_pos = pos
    self.image = Image.open(image_path)
    self.photoimage = ImageTk.PhotoImage(self.image)
    self.image_obj = self.canvas.create_image((self.image_pos[0], self.image_pos[1]), image=self.photoimage)


    If I don't mention a variable name for the instance of CreateImage it won't display

    if __name__ == "__main__":
    root = tk.Tk()
    path = 'original.jpg'
    root.geometry('600x600')
    cvs = tk.Canvas(root, background="bisque")
    cvs.pack(fill="both", expand=True)
    CreateImage(cvs, path)
    root.mainloop()


    But if I write it like img1 = CreateImage(cvs, path) it works.

    Continue reading...

Compartilhe esta Página