我正试图在我的应用程序中加载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=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
如何在两个窗口中都添加图像?
发布于 2020-11-18 14:33:46
这是因为您有两个Tk()
实例。在bar()
中使用Toplevel()
。
此外,mainloop()
不能在线程中执行,因此请从bar()
中删除app.mainloop()
。
最后,您需要保留img2
的引用,否则它将被垃圾回收。
以下是基于您的更新代码:
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():
time.sleep(5)
root.withdraw()
app = Toplevel()
app.withdraw()
img2 = PhotoImage(file='./images/night_bulb.png')
label3 = Label(app, image=img2)
label3.pack()
label3.image = img2 # keep a reference to avoid garbage collection
Label(app, text='Starting Count now...').pack()
app.deiconify()
foo()
https://stackoverflow.com/questions/64887920
复制相似问题