pysimpleGUI - 即时创建线程

pysimpleGUI - creating a thread on the fly

我使用 PysimpleGUI 创建了一个具有多个按钮的 GUI,目的是用户单击一个按钮并继续处理其他任务,而第一个单击按钮的操作是 运行,当点击按钮的动作结束,线程退出(distroys当前线程),

代码抛出:运行时错误:主线程不在主循环中

谁能帮我创建 _thread.start_new_thread 进程并合并到主循环中,或者可能是避免 RuntimeError

的解决方案

我正在使用线程:_thread

代码:

class Windows:

    def newOpenGraph(self, window, event, values):
        '''
        opens a new graph with no problem
        '''

    def newThread(self, window, event, values):

        isRunning = True
        if event == 'OPEN GRAPH':
            _thread.start_new_thread(self.newOpenGraph, (window, event, values ))
        isRunning = False

        while isRunning:
            schedule.run_pending()
            time.sleep(1)

    def mainLayout(self):
        '''
        layout frame work
        '''

        while True:

            event, values = window.read()
            if event == 'OPEN GRAPH':
                # self.newOpenGraph(window, event, values)
                self.newThread(window, event, values)

图片:

在你的线程中使用库 schedule,而不是在主循环中,也没有在你的线程中更新 GUI。

也许这样的代码,

import time
import _thread
import schedule
import PySimpleGUI as sg

def func(window):
    global i
    window.write_event_value('Update', i)
    i += 1

def new_thread(window, event, values):
    global running
    schedule.every().second.do(func, window=window)
    running = True
    while running:
        schedule.run_pending()
        time.sleep(0.1)

layout = [
    [sg.Button("New"), sg.Button('Exit')],
    [sg.Text('', size=40, key='STATUS')],
]

window = sg.Window("Multithread", layout, finalize=True)
i = 0
threads = []
while True:

    event, values = window.read(timeout=100)

    if event in (sg.WIN_CLOSED, 'Exit'):
        running = False
        break
    elif event == 'New':
        _thread.start_new_thread(new_thread, (window, event, values))
    elif event == 'Update':
        window['STATUS'].update(f'Index {values[event]}')

window.close()