Python Tkinter更新图像

时间:2015-03-04 18:11:31

标签: python-3.x tkinter

我在tkinter中更新画布中的图片时遇到问题。我正在使用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() 

首先图像可见,但按下按钮后,图像变为空白。我读过许多类似的问题,但没有一个有任何帮助。

1 个答案:

答案 0 :(得分:2)

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

def changeImg(self):

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

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