如何使用Python Tkinter更有效地创建图像显示器? [英] How to create an image displayer using Python Tkinter more efficiently?

查看:53
本文介绍了如何使用Python Tkinter更有效地创建图像显示器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import tkinter as tk
from PIL import ImageTk, Image
root = tk.Tk()

def photogetter():
    ###global photo

    photo= ImageTk.PhotoImage(Image.open("smiley.png").resize((320,240)))
    label =tk.Label(root,image=photo)
    canv.create_window((320,240),window=label)
    

canv = tk.Canvas(root,width=640,height=480)
canv.grid(row=0,column=0)

button = tk.Button(root,text="Button",command=photogetter)
button.grid(row=1,column=0)

root.mainloop()

除非我在函数中将 photo 变量声明为全局变量,否则此代码无效.有人可以向我解释为什么我必须将 photo 变量声明为全局变量吗?对我来说,使用局部变量看起来更有效,但这不起作用.

This code does not work unless I declare the photo variable as global in my function. Can somebody explain me why do I have to declare the photo variable as global? Using local variables look more efficient to me, but it does not work.

推荐答案

这是因为当 photo 不是 global 时,它是python垃圾收集器进行的垃圾收集,因此您需要保留对图像的引用,可以通过说 global image label.image = photo 来做到.无论哪种方式,您都只需要保留一个引用,以免被垃圾收集.

This is because when photo is not global it is garbage collected by the python garbage collector hence you need to keep reference to the image, this can be done so by saying global image or label.image = photo. Either way you just have to keep a reference so that it is not garbage collected.

global 对于OOP可能不是有效的,因为它稍后可能会引起一些问题,这是我所听到的,因此您可以通过 label.image = photo 保留引用.

global might not be efficient with OOP as it could create some issues later, is what i heard, so you can keep a reference by label.image = photo.

来自effbot.org:

问题在于Tkinter/Tk界面无法正确处理对Image对象的引用;Tk小部件将保留对内部对象的引用,但Tkinter不会.当Python的垃圾收集器丢弃Tkinter对象时,Tkinter告诉Tk释放图像.但是由于小部件正在使用该图像,因此Tk不会销毁它.不完全的.它只是使图像空白,使其完全透明.

The problem is that the Tkinter/Tk interface doesn’t handle references to Image objects properly; the Tk widget will hold a reference to the internal object, but Tkinter does not. When Python’s garbage collector discards the Tkinter object, Tkinter tells Tk to release the image. But since the image is in use by a widget, Tk doesn’t destroy it. Not completely. It just blanks the image, making it completely transparent.

希望这可以解决您的疑问.

Hope this solved your doubts.

欢呼

这篇关于如何使用Python Tkinter更有效地创建图像显示器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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