【问题标题】:python tkinter with canvas not showing images带有画布的python tkinter不显示图像
【发布时间】:2021-12-31 17:27:42
【问题描述】:

从数据库中检索图像并渲染所有图像不显示时,我遇到了“tkinter”和“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

【问题讨论】:

  • 这段代码在函数中吗?

标签: python tkinter canvas


【解决方案1】:

这些图像在退出类方法后被垃圾收集(因为您在代码中使用了self)。使用列表(实例变量)来存储这些图像:

    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

【讨论】:

    猜你喜欢
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2015-11-29
    • 2013-12-02
    • 1970-01-01
    相关资源
    最近更新 更多