我用 PysimpleGUI 创建了一个具有多个按钮的 GUI,其目的是用户单击一个按钮并在第一个单击按钮的操作正在运行时继续处理其他任务,并且当单击按钮的操作完成时,然后执行绪退出(破坏当前执行绪),
代码抛出:RuntimeError:主执行绪不在主回圈中
有人可以帮我创建 _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)
图片:
uj5u.com热心网友回复:
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()
947 评论