Python 3.x 在tkinter中加载带有线程显示的图像';pyimage2';不';不存在
我正在尝试在我的应用程序中加载2个图像,第一个在主窗口中,第二个在线程中 代码如下:Python 3.x 在tkinter中加载带有线程显示的图像';pyimage2';不';不存在,python-3.x,tkinter,Python 3.x,Tkinter,我正在尝试在我的应用程序中加载2个图像,第一个在主窗口中,第二个在线程中 代码如下: from tkinter import * import threading import time def foo(): global root root = Tk() img1 = PhotoImage(file='Logo.png') lable1 = Label(root, image = img1).pack() threading.Thread(target
from tkinter import *
import threading
import time
def foo():
global root
root = Tk()
img1 = PhotoImage(file='Logo.png')
lable1 = Label(root, image = img1).pack()
threading.Thread(target=bar).start()
root.mainloop()
def bar():
app = Tk()
app.withdraw()
time.sleep(5)
app.deiconify()
root.withdraw()
img2 = PhotoImage(file='./images/night_bulb.png')
lable3 = Label(app, image= img2).pack()
lable2 = Label(app, text='Starting Count now...').pack()
app.mainloop()
foo()
这将产生以下输出:
"C:\Users\Samaksh Gupta\PycharmProjects\myIDLE\venv\Scripts\python.exe" "C:/Users/Samaksh Gupta/PycharmProjects/myIDLE/test.py"
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\Samaksh Gupta\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Samaksh Gupta\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:/Users/Samaksh Gupta/PycharmProjects/myIDLE/test.py", line 20, in bar
lable3 = Label(app, image= img2).pack()
File "C:\Users\Samaksh Gupta\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 3143, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\Samaksh Gupta\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 2567, in __init__
self.tk.call(
_tkinter.TclError: image "pyimage2" doesn't exist
如何在两个窗口中添加图像?这是因为您有两个
Tk()
的实例。使用Toplevel()
代替bar()
而且mainloop()
不能在线程中执行,因此请从bar()
中删除app.mainloop()
最后,您需要保留img2
的引用,否则它将被垃圾收集
以下是基于您的更新代码:
从tkinter导入*
导入线程
导入时间
def foo():
全局根
root=Tk()
img1=PhotoImage(文件='Logo.png')
lable1=Label(root,image=img1).pack()
threading.Thread(target=bar).start()
root.mainloop()
def bar():
时间。睡眠(5)
root.draw()
app=Toplevel()
app.draw()
img2=PhotoImage(文件='。/images/night\u bulb.png')
标签3=标签(应用程序,图像=img2)
标签3.pack()
label3.image=img2#保留引用以避免垃圾收集
标签(app,text='Starting Count now…').pack()
附录.deiconify()
foo()
这是因为您有两个Tk()
的实例。使用Toplevel()
代替bar()
。而且mainloop()
不能在线程中执行,因此请删除app.mainloop()
。最后,您需要保存img2
的引用,否则它将被垃圾收集。实际上,您不应该使用thread来运行bar()
,而应该使用after()
@acw1668,我试过了。现在窗口打开,没有错误出现。但是图像不会加载太多。它只是显示的标签。正如我说的“你需要保存img2的引用,否则它将被垃圾收集”。@acw1668我需要在我的主应用程序中使用线程。当tk加载时,它有大量图像和动画GIF,窗口会挂起7-10秒。我需要另一个窗口显示信息“加载”和图像。在这7-10秒的时间内,我的应用程序窗口将使用draw
命令保持隐藏。@acw1668抱歉,刷新页面后看到了您的编辑。如何保存img2的引用?@SamakshGupta在foo()中添加time.sleep(5)
下面root=Tk()。