问题描述
限时送ChatGPT账号..我注意到 tkinter 有一个非常奇怪的错误,我想知道这是否是因为 Python 与 tcl 的交互方式存在某些问题,至少在 Win32 中是这样.
I'm noticing a pretty strange bug with tkinter, and I am wondering if it's because there's something in how the python interacts with the tcl, at least in Win32.
这里我有一个超级简单的程序,可以显示 gif 图像.它完美运行.
Here I have a super simple program that displays a gif image. It works perfectly.
from Tkinter import *
canvas = Canvas(width=300, height=300, bg='white')
canvas.pack()
photo=PhotoImage(file=sys.argv[1])
canvas.create_image(0, 0, image=photo, anchor=NW) # embed a photo
print canvas
print photo
mainloop( )
现在,我稍微更改程序以从函数内编辑画布对象.这一次,我只得到一张空白画布.
Now, I change the program slightly to edit the canvas object from within a function. This time, I just get a blank canvas.
# demo all basic canvas interfaces
from Tkinter import *
canvas = Canvas(width=300, height=300, bg='white')
canvas.pack()
def set_canvas(cv):
photo=PhotoImage(file=sys.argv[1])
cv.create_image(0, 0, image=photo, anchor=NW) # embed a photo
print cv
print photo
set_canvas(canvas)
mainloop( )
两者之间的唯一区别在于,在其中一个画布对象被传递给一个函数,而不是被直接使用.两个打印语句返回相同的结果.我想知道 tcl/python 层的对象模型是否可能存在一些故障.
The only difference between the two is that in one the canvas object is passed to a function instead of being used directly. Both print statements return identical results. I am wondering if there is perhaps some breakdown in the object model at the tcl/python layer.
各位有什么想法吗?
谢谢,/YGA
推荐答案
这样做是一个快速的解决方案,我会尝试解释:
Do that as a quick solution, and I'll try to explain:
def set_canvas(cv):
global photo # here!
photo=PhotoImage(file=sys.argv[1])
cv.create_image(0, 0, image=photo, anchor=NW) # embed a photo
print cv
print photo
PhotoImage 需要至少有一个来自任何 Python 对象的引用,否则它会被垃圾收集.在我的解决方案中,我建议将 photo
设为模块级名称,这样当函数结束时,仍然会有对 PhotoImage 对象的引用.您可能更喜欢创建一个类并将 set_canvas
变成一个方法,并将 PhotoImage 对象存储为实例变量.
A PhotoImage needs to have at least one reference from any Python object, otherwise it's garbage collected. In my solution, I suggest to make photo
be a module-level name, so when the function ends, there will still be a reference to the PhotoImage object. You might prefer to create a class and make set_canvas
into a method, and store the PhotoImage object as an instance variable.
这篇关于在画布上显示照片是否存在已知的 Win32 Tkinter 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论