在画布上显示照片是否存在已知的 Win32 Tkinter 错误?

编程入门 行业动态 更新时间:2024-10-19 19:47:38
本文介绍了在画布上显示照片是否存在已知的 Win32 Tkinter 错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

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

发布评论

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

>www.elefans.com

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