Python Tkinter 更新镜像

编程入门 行业动态 更新时间:2024-10-28 05:17:42
本文介绍了Python Tkinter 更新镜像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我在 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 06:17:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390865.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:镜像   Python   Tkinter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!