Python Tkinter 更新图片

Python Tkinter update image

我在 tkinter canvas 中更新图片时遇到问题。我正在使用 Python 3.3.

from tkinter import *

class Testi():
    def __init__(self):
        self.canvas = Canvas(root, width = 800, height = 480)
        self.img = PhotoImage(file="title.pgm")
        self.imgArea = self.canvas.create_image(0, 0, anchor = NW, image = self.img)
        self.canvas.pack()
        self.but1 = Button(root, text="press me", command=lambda: self.changeImg())
        self.but1.place(x=10, y=500)

    def changeImg(self):
        newimg = PhotoImage(file="cell.pgm")
        self.canvas.itemconfig(self.imgArea, image = newimg)

root = Tk()
root.geometry("800x600")
app = Testi()
root.mainloop() 

起初图像是可见的,但按下按钮后,图像变为空白。我读过很多类似的问题,但其中 none 有任何帮助。

与原始图像一样,您需要保留对新图像的引用,否则它会过早地被垃圾收集。只需覆盖位于 self.img.

的旧图像
def changeImg(self):

    self.img = PhotoImage(file="cell.pgm")

    self.canvas.itemconfig(self.imgArea, image = self.img)