首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在带有线程的tkinter中加载图像显示'pyimage2‘不存在

在带有线程的tkinter中加载图像显示'pyimage2‘不存在
EN

Stack Overflow用户
提问于 2020-11-18 14:06:05
回答 1查看 111关注 0票数 0

我正试图在我的应用程序中加载2个图像,第一个在主窗口,第二个在一个线程中。

代码如下:

代码语言:javascript
运行
复制
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()

这将生成以下输出:

代码语言:javascript
运行
复制
"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

如何在两个窗口中都添加图像?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-18 14:33:46

这是因为您有两个Tk()实例。在bar()中使用Toplevel()

此外,mainloop()不能在线程中执行,因此请从bar()中删除app.mainloop()

最后,您需要保留img2的引用,否则它将被垃圾回收。

以下是基于您的更新代码:

代码语言:javascript
运行
复制
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()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64887920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档