控制台应用程序主线程不在使用 pysimplegui 的主循环中

console application main thread is not in main loop using pysimplegui

几天来,我一直在研究如何解决这个问题。基本上我有一个控制台应用程序,在某些阶段,我调用 pysimplegui 来创建通知 window 或:

  1. 需要一直在后台运行的主控制台程序
  2. 如果捕获即击键,则创建警报 window。在这个阶段,我需要主控制台程序在创建 pysimplegui window 时仍然捕获击键。因此,为什么我使用线程在新线程中打开 pysimplegui window。

我是如何开发程序的。

if (threading.active_count() < 2):
    wt = threading.Thread(target=createwindow, name="noty", args=(argumnets,),
                                          daemon=True)
    wt.setDaemon(True) # just to be safe
    wt.start()
    wt.join()

创建 window:

def createalertwindow(Attack):
    # I have removed this part of the code where I design the gui window just to make easy to understand
    e, v = win.read(timeout=5000)
    if (e == "e"):
        print("e button clicked")
    elif (e == "Ok"):
        win.close()
    # close first window
    win.close()

现在每次我 运行 以上代码都会出现以下异常错误:

Exception ignored in: <function Variable.del at 0x000001EACB37CCA0> Traceback (most recent call last): File "C:\Users\Abdul\AppData\Local\Programs\Python\Python39\lib\tkinter_init_.py", line 350, in del if self._tk.getboolean(self._tk.call("info", "exists", self.name)): RuntimeError: main thread is not in main loop Exception ignored in: <function Variable.del at 0x000001EACB37CCA0> Traceback (most recent call last): File "C:\Users\Abdul\AppData\Local\Programs\Python\Python39\lib\tkinter_init.py", line 350, in del if self._tk.getboolean(self._tk.call("info", "exists", self._name)): RuntimeError: main thread is not in main loop

我已经阅读了很多问题,但发现 none 可以为我解决问题,即我尝试使用:

plt.switch_backend('agg')

wt = threading.Thread(target=createwindow, name="noty", args=(argumnets,),
                                          daemon=True)
wt.setDaemon(True)
...

值得一提的是我的主程序是控制台应用程序而不是 gui 应用程序。

我正在使用线程库进行线程处理,但如果我有更好的选择并且正在使用 pysimplegui 来创建 gui,我可以切换 windows。

您似乎无法在另一个线程中调用 PySimpleGUI/tkinter。 这里,尝试将主程序设置为一个线程并在PySimpleGUI/tkinter中调用。 同样,请记住不要在 main_program 中直接调用 PySimpleGUI 并使用方法 window.write_event_value 生成事件,然后在事件循环中执行。

示例代码,

from time import sleep
import threading
import PySimpleGUI as sg

def hello():
    layout = [[sg.Text("Hello, my friend !")]]
    window = sg.Window("Hello", layout, keep_on_top=True, modal=True)
    window.read(timeout=1000, close=True)

def main_program():
    count = 5
    while count > 0:
        window.write_event_value("Hello", None)
        sleep(3)
        count -=1
    window.write_event_value(sg.WINDOW_CLOSED, None)

layout = [[]]

window = sg.Window("Title", layout, alpha_channel=0, finalize=True)
threading.Thread(target=main_program, daemon=True).start()
while True:

    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    elif event == "Hello":
        hello()

window.close()