Python Tkinter 错误“pyimage2 deos 不存在”

问题描述 投票:0回答:1

我一直在做一个小项目,遇到了一个错误。作为 tkinter 的新手,我不知道这意味着什么。错误的详细信息和导致该错误的代码如下。

这是我的完整错误:

Traceback (most recent call last):
  File "D:\red zone\main.py", line 5, in <module>
    b = updateError((500,500))
  File "D:\red zone\scripts\windows.py", line 44, in __init__
    self.widget["image"] = self.widget.errorImage
  File "C:\Users\maude_u0wvgig\AppData\Local\Programs\Python\Python312\Lib\tkinter\__init__.py", line 1727, in __setitem__
    self.configure({key: value})
  File "C:\Users\maude_u0wvgig\AppData\Local\Programs\Python\Python312\Lib\tkinter\__init__.py", line 1716, in configure
    return self._configure('configure', cnf, kw)
  File "C:\Users\maude_u0wvgig\AppData\Local\Programs\Python\Python312\Lib\tkinter\__init__.py", line 1706, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: image "pyimage2" doesn't exist

这是我的目录结构:

\folder1
    err.png
\folder2
    windows.py
main.py

我的Python文件代码:

windows.py

## imports
import base64
import os
import tempfile
import time
import tkinter as tk
import zlib
from tkinter import *
from tkinter import ttk

class updateError():
    def __init__(self, isTk=False, pos=[500,500]):
        ## variables
        self.ICON = zlib.decompress(base64.b64decode('eJxjYGAEQgEBBiDJwZDBy'
            'sAgxsDAoAHEQCEGBQaIOAg4sDIgACMUj4JRMApGwQgF/ykEAFXxQRc='))
        ## main program
        # window setup
        self._, self.ICON_PATH = tempfile.mkstemp()
        with open(self.ICON_PATH, 'wb') as self.icon_file:
            self.icon_file.write(self.ICON)
        if isTk:
            self.root = Tk()
        elif not isTk:
            self.root = Toplevel()
        elif type(isTk) is not bool:
            raise TypeError(f"needs bool, not {type(isTk)}")
        if not 0 <= pos[0] <= 900:
            raise ValueError("x position must be between 0 and 900")
        elif not 0 <= pos[1] <= 750:
            raise ValueError("y position must be between 0 and 750")
        self.frm = ttk.Frame(self.root, padding=10)
        self.frm.grid()
        # window content
        ttk.Label(self.frm, text="Windows was not installed properly. Please reinstall Windows.\nError 4 (Windows error 096)").grid(column=1, row=0)
        ttk.Button(self.frm, text="Ok").grid(column=5, row=3)
        # window config
        self.root.geometry(f"+{pos[0]}+{pos[1]}")
        self.root.title("Microsoft Windows")
        self.root.resizable(width=False, height=False)
        self.root.iconbitmap(default=self.ICON_PATH)

        self.widget = ttk.Label(self.frm)
        self.widget.errorImage = tk.PhotoImage(file=r"assets\err.png")
        self.widget["image"] = self.widget.errorImage
        self.widget.grid(column=0, row=0)

        self.root.after(1, lambda: self.root.focus_force())

主.py

## imports
from scripts.windows import updateError
 
a = updateError(True, (900,750))
b = updateError((500,500))

这确实有效,因为它按预期创建了两个窗口,但其中一个窗口丢失了图像,并且两个窗口都没有设置自定义图标。

预期的操作系统是 Windows,但我更喜欢跨平台解决方案。

python python-3.x tkinter
1个回答
0
投票

当您尝试在同一线程中启动

tkinter
窗口的多个实例时,会发生此错误,因此
b
实例找不到
pyimage2
,因为
a
实例已经在运行它。您可以通过在
tkinter
窗口中引入多线程来解决此问题。像这样修改你的 main.py:

import threading
from scripts.windows import updateError
import tkinter as tk


def create_update_error_window(isTk, pos):
    error_window = updateError(isTk, pos)
    error_window.root.mainloop()

# Function to start threads
def start_threads():
    thread_a = threading.Thread(target=create_update_error_window, args=(True, (900, 750)))
    thread_b = threading.Thread(target=create_update_error_window, args=(False, (500, 500)))
    thread_a.start()
    thread_b.start()
    thread_a.join()
    thread_b.join()

if __name__ == "__main__":
    # Start Tkinter in the main thread
    root = tk.Tk()
    root.withdraw()  # Hide the main Tk window
    
    # Start error window threads
    start_threads()

    # Start the main loop
    root.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.