Python Tkinter 更新镜像 [英] Python Tkinter update image

查看:27
本文介绍了Python Tkinter 更新镜像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 tkinter 中更新画布中的图片时遇到问题.我使用的是 Python 3.3.

I have problem with updating picture in canvas in tkinter. I'm using 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() 

一开始图像是可见的,但按下按钮后,它变成了空白.我读过很多类似的问题,但没有一个有任何帮助.

At first the image is visible but after pressing button, it goes blank. I have read many similar questions but none of those had any help.

推荐答案

和原图一样,需要保留对新图的引用,否则会过早地被垃圾回收.只需覆盖 self.img 中的旧图像即可.

Like the original image, you need to keep a reference to the new image, or it will get garbage collected prematurely. Just overwrite the old image sitting at self.img.

def changeImg(self):

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

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

这篇关于Python Tkinter 更新镜像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆