本文介绍了如何更新 Tkinter 画布上的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个脚本,使我能够动态更新图像对象,然后将更新后的图像发布到 Tkinter Canvas 小部件.这里的代码是原型代码,只是为了了解基础.这里的目的是在画布显示的图像上的单击位置放置一个蓝色像素.

I'm trying to make a script which will enable me to dynamically update an image object and then post the updated image to a Tkinter Canvas widget. The code here is prototype code, just to get the basics down. The aim here is to put a blue pixel on the image being displayed by the canvas, at the click location.

这里发生了一些非常奇怪的事情.我正在使用 Wing IDE,如果我通过调试器运行此代码,并在 woohoo 函数的任何行处设置断点,然后在断点后继续执行,则代码的工作方式完全相同预期 - 在图像上放置一个蓝色像素.如果我正常运行代码,或者通过没有断点的调试器,图像永远不会更新.这使我得出结论,有一些内在的魔法正在发生,如果没有帮助,我没有太大希望去理解.

Something very strange is going on here. I'm using the Wing IDE, and if I run this code through the debugger, with a breakpoint at any line in the woohoo function, and then continue execution after hitting the breakpoint, the code works exactly as expected- putting a blue pixel on the image. If I run the code normally, or through the debugger with no breakpoints, the image is never updated. This leads me to the conclusion that there is some internal wizardry going on which I haven't got much hope of understanding without aid.

我真的很想知道解决这个问题的最佳方式(或任何方式,我猜),如果有人能向我解释引擎盖下发生的事情,那就太酷了.谢谢.

I'd really like to know the best way to go about this (or any way, I guess), and if someone could explain to me what's going on under the hood that'd be really cool. Thanks.

from Tkinter import *
from PIL import Image, ImageTk

def woohoo(event):

    original.putpixel((event.x,event.y),(0,0,255))

    newpic = ImageTk.PhotoImage(original)
    c.create_image((0,0),image=newpic, anchor="nw")


main = Tk()
c = Canvas(main, width=300, height=300)
main.geometry("300x300+0+0")
c.pack()

original = Image.open("asc.bmp")
picture = ImageTk.PhotoImage(original)
c.create_image((0,0),image=picture, anchor="nw")

c.bind("<Button-1>", woohoo)

main.mainloop()

推荐答案

我的猜测是,您正在函数中创建一个新图像.对图像的引用是一个局部变量.当函数退出时,引用被垃圾收集,这会导致新图像被销毁.最有可能的是,以交互方式运行会导致垃圾收集器以不同方式运行(也许更懒惰?)

My guess is, you're creating a new image in a function. The reference to the image is a local variable. When the function exits, the reference is garbage collected which causes the new image to be destroyed. Most likely, running interactively causes the garbage collector to run differently (perhaps more lazily?)

这篇关于如何更新 Tkinter 画布上的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 15:19