Python Tkinter主循环和映像打包必须在同一代码段中?
以下示例根本不会显示图像:Python Tkinter主循环和映像打包必须在同一代码段中?,python,tkinter,Python,Tkinter,以下示例根本不会显示图像: from tkinter import * def main(root): img = PhotoImage(file="image.png") Label(image=img).pack() if __name__ == "__main__": root = Tk() main(root) root.mainloop() 但是,如果我将mainloop移动到main中,或者
from tkinter import *
def main(root):
img = PhotoImage(file="image.png")
Label(image=img).pack()
if __name__ == "__main__":
root = Tk()
main(root)
root.mainloop()
但是,如果我将mainloop
移动到main
中,或者在函数外部执行它们,它就会工作:
root = Tk()
img = PhotoImage(file="image.png")
Label(image=img).pack()
root.mainloop()
也尝试使用网格
,但存在相同问题。有人能解释一下这背后的原因吗,还是我遗漏了什么?这是
PhotoImage
垃圾收集器的常见问题,垃圾收集器将图像分配给局部变量(函数中创建的变量)时,会从内存中删除图像。您必须将图像分配给全局变量或某个对象,例如,分配给显示图像的标签:
label = Label(...)
label.img = PhotoImage(..)
最少的工作示例
from tkinter import *
def main(root):
global img # <-- solution for bug
img = PhotoImage(file="image.png")
Label(image=img).pack()
if __name__ == "__main__":
root = Tk()
main(root)
root.mainloop()
从tkinter导入*
def主(根):
全局img#当图像分配给局部变量(函数中创建的变量)时,PhotoImage
中的垃圾收集器将图像从内存中删除,这是一个常见问题。您必须将图像分配给全局变量或某个对象,例如,分配给显示图像的标签:
label = Label(...)
label.img = PhotoImage(..)
最少的工作示例
from tkinter import *
def main(root):
global img # <-- solution for bug
img = PhotoImage(file="image.png")
Label(image=img).pack()
if __name__ == "__main__":
root = Tk()
main(root)
root.mainloop()
从tkinter导入*
def主(根):
全局img#在PhotoImage
中存在垃圾收集器的常见错误,当图像分配给局部变量(在函数中创建的变量)时,会从内存中删除图像。您必须将图像分配给全局变量或其他类-即。label=label(…)
和label.img=PhotoImage(…)
图像不会显示,因为它在函数返回后被垃圾收集。但是,如果将mainloop()
放入main()
,则函数不会返回,因为mainloop()
会阻止应用程序。在这种情况下,可以显示图像。PhotoImage
中垃圾收集器的常见错误,当图像分配给局部变量(函数中创建的变量)时,该错误会从内存中删除图像。您必须将图像分配给全局变量或其他类-即。label=label(…)
和label.img=PhotoImage(…)
图像不会显示,因为它在函数返回后被垃圾收集。但是,如果将mainloop()
放入main()
,则函数不会返回,因为mainloop()
会阻止应用程序。在这种情况下,可以显示图像。太棒了,谢谢你的帮助!我从2020年11月12日在Wayback机器中发现了旧的effbot.org:参见关于bug的注释。尼斯参考资料太棒了,谢谢你的帮助!我从2020.11.12在Wayback机器中发现了旧的effbot.org:参见关于bug.nice参考的注释