如何更有效地使用 Python Tkinter 创建图像显示器?
How to create an image displayer using Python Tkinter more efficiently?
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 变量声明为全局变量吗?使用局部变量对我来说看起来更有效,但它不起作用。
这是因为当 photo
不是 global
时,它是由 python 垃圾收集器收集的垃圾,因此您需要保持对图像的引用,这可以通过说 global image
或 label.image = photo
。无论哪种方式,您只需要保留一个引用,这样它就不会被垃圾收集。
global
对于 OOP 可能效率不高,因为它可能会在以后产生一些问题,这是我听说的,因此您可以通过 label.image = photo
.
保留参考
来自 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.
希望这能解决你的疑惑。
干杯
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 变量声明为全局变量吗?使用局部变量对我来说看起来更有效,但它不起作用。
这是因为当 photo
不是 global
时,它是由 python 垃圾收集器收集的垃圾,因此您需要保持对图像的引用,这可以通过说 global image
或 label.image = photo
。无论哪种方式,您只需要保留一个引用,这样它就不会被垃圾收集。
global
对于 OOP 可能效率不高,因为它可能会在以后产生一些问题,这是我听说的,因此您可以通过 label.image = photo
.
来自 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.
希望这能解决你的疑惑。
干杯