问题
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