How to create an image displayer using Python Tkinter more efficiently? [duplicate]

北城余情 提交于 2021-01-29 11:23:46

问题


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()

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.


回答1:


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 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.

From effbot.org:

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.

Cheers



来源:https://stackoverflow.com/questions/63753469/how-to-create-an-image-displayer-using-python-tkinter-more-efficiently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!