Home > Net >  python tkinter with canvas not showing images
python tkinter with canvas not showing images

Time:11-24

I have a problems with "tkinter" and "canvas" when retrieve images from database and render all images not show. When debugging a code all images showing normally, but execute code imagens not show in canvas.

    count = 0
    posx = 1
    posy = 5
    for imagem in self.imagens:

        img1 = Image.open(imagem[2])
        img1 = img1.resize((200, 200), Image.ANTIALIAS)
        photoImage = ImageTk.PhotoImage(img1)

        self.canvas.create_image(posy, posx, anchor=NW, image=photoImage)

        count = count   1
        if count == 9:
            break

        if count == 0 or count == 3 or count == 6:
            posy = 5
        elif count == 1 or count == 4 or count == 7:
            posy = 210
        elif count == 2 or count == 5 or count == 8:
            posy = 415

        if count > 2 and count < 5:
            posx = 205
        elif count > 5 and count < 8:
            posx = 410

CodePudding user response:

Those images are garbage collected after exiting the class method (as you have used self in the code). Use a list (an instance variable) to store those images:

    count = 0
    posx = 1
    posy = 5
    self.imagelist = []  # for storing those images
    for imagem in self.imagens:

        img1 = Image.open(imagem[2])
        img1 = img1.resize((200, 200), Image.ANTIALIAS)
        photoImage = ImageTk.PhotoImage(img1)
        self.imagelist.append(photoImage) # save the reference of the image

        self.canvas.create_image(posy, posx, anchor=NW, image=photoImage)

        count = count   1
        if count == 9:
            break

        if count == 0 or count == 3 or count == 6:
            posy = 5
        elif count == 1 or count == 4 or count == 7:
            posy = 210
        elif count == 2 or count == 5 or count == 8:
            posy = 415

        if count > 2 and count < 5:
            posx = 205
        elif count > 5 and count < 8:
            posx = 410
  • Related