ошибка

XXX lineno: 117, opcode: 123
Traceback (most recent call last):
  File "C:\Users\kapralovpa\PycharmProjects\WinAuto\Win\gui\startup_progress.py", line 48, in run_preparation
    self.update_status("Поиск процесса EzCad2...")
  File "C:\Users\kapralovpa\PycharmProjects\WinAuto\Win\gui\startup_progress.py", line 44, in update_status
    self.after(0, lambda: self.status_label.config(text=text))
  File "C:\Users\kapralovpa\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 821, in after
    name = self._register(callit)
  File "C:\Users\kapralovpa\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1528, in _register
    self.tk.createcommand(name, f)
RuntimeError: main thread is not in main loop
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\kapralovpa\AppData\Local\Programs\Python\Python39\lib\threading.py", line 917, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\kapralovpa\PycharmProjects\WinAuto\Win\gui\startup_progress.py", line 117, in run_preparation
    self.finish_with_error(f"Ошибка: {e}")
SystemError: unknown opcode
Exception in thread Thread-5:
Traceback (most recent call last):
  File "C:\Users\kapralovpa\PycharmProjects\WinAuto\Win\gui\startup_progress.py", line 48, in run_preparation
    self.update_status("Поиск процесса EzCad2...")
  File "C:\Users\kapralovpa\PycharmProjects\WinAuto\Win\gui\startup_progress.py", line 44, in update_status
    self.after(0, lambda: self.status_label.config(text=text))
  File "C:\Users\kapralovpa\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 821, in after
    name = self._register(callit)
  File "C:\Users\kapralovpa\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1528, in _register
    self.tk.createcommand(name, f)
RuntimeError: main thread is not in main loop
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\kapralovpa\AppData\Local\Programs\Python\Python39\lib\threading.py", line 980, in _bootstrap_inner
    self.run()
  File "C:\Users\kapralovpa\AppData\Local\Programs\Python\Python39\lib\threading.py", line 917, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\kapralovpa\PycharmProjects\WinAuto\Win\gui\startup_progress.py", line 117, in run_preparation
    self.finish_with_error(f"Ошибка: {e}")
SystemError: unknown opcode



import tkinter as tk
from tkinter import ttk, messagebox
import threading
import time
import logging
import win32gui

from Win.app_state import state
from Win.app_finder import (
    find_target_process,
    find_target_elements
)
from Win.hooks import HookManager

from Win.win_utils import enable_window, activate_window

logger = logging.getLogger(__name__)

class StartupProgress(tk.Toplevel):
    def __init__(self, parent):
        super().__init__(parent)
        self.title("Подготовка программы")
        self.geometry("400x150")
        self.resizable(False, False)
        self.protocol("WM_DELETE_WINDOW", self.on_close)

        self.progress = ttk.Progressbar(self, length=350, mode='determinate', maximum=4)
        self.progress.pack(pady=20)

        self.status_label = tk.Label(self, text="Инициализация...")
        self.status_label.pack(pady=5)

        self.cancelled = False
        self.success = False

        self.thread = threading.Thread(target=self.run_preparation, daemon=True)
        self.thread.start()

    def on_close(self):
        if messagebox.askokcancel("Отмена", "Прервать запуск программы?"):
            self.cancelled = True

    def update_status(self, text):
        self.after(0, lambda: self.status_label.config(text=text))

    def run_preparation(self):
        try:
            self.update_status("Поиск процесса EzCad2...")
            for _ in range(10):
                if self.cancelled:
                    self.finish_with_error("Запуск отменён пользователем.")
                    return
                main_win, pid = find_target_process()
                if main_win:
                    state.main_win = main_win.handle
                    state.pid = pid
                    break
                time.sleep(0.5)
            else:
                self.finish_with_error("Процесс EzCad2 не найден.")
                return

            enable_window(state.main_win, False)
            activate_window(state.main_win)
            self.progress.step(1)

            self.update_status("Поиск целевых элементов...")
            for _ in range(10):
                if self.cancelled:
                    enable_window(state.main_win, True)
                    self.finish_with_error("Запуск отменён пользователем.")
                    return
                target_element, target_button = find_target_elements(state.main_win)
                if target_element and target_button:
                    state.target_element = target_element.handle
                    state.target_button = target_button.handle
                    break
                time.sleep(0.5)
            else:
                enable_window(state.main_win, True)
                self.finish_with_error("Целевые элементы не найдены.")
                return
            self.progress.step(1)

            self.update_status("Проверка камеры (внедрить позже)...")
            # if not self.check_camera():
            #     enable_window(self.target_hwnd, True)
            #     self.finish_with_error("Камера не подключена.")
            #     return
            self.progress.step(1)

            self.update_status("Установка хуков...")
            hooks = HookManager(lambda: state.target_element, lambda: state.target_button)
            if not hooks.install_keyboard_hook() or not hooks.install_win_event_hook(pid):
                if hooks: hooks.remove_keyboard_hook(); hooks.remove_win_event_hook()
                hooks = None
                time.sleep(2)

                enable_window(state.main_win, True)
                self.finish_with_error("Хуки не были уставнолены.")
                return

            self.update_status("Хуки успешно установлены")

            self.progress.step(1)

            self.update_status("Готово.")
            time.sleep(0.5)

            enable_window(state.main_win, True)
            self.success = True
            self.after(100, self.destroy)

        except Exception as e:
            logger.error(f"Ошибка подготовки: {e}")
            enable_window(state.main_win, True)
            self.finish_with_error(f"Ошибка: {e}")

    def finish_with_error(self, message):
        def show_error():
            messagebox.showerror("Ошибка запуска", message, parent=self)
            self.destroy()

        self.after(0, show_error)

    def default_check_camera(self):
        # Заглушка, заменить на реальную проверку камеры
        time.sleep(1)
        return True