【问题标题】:pysimpleGUI - creating a thread on the flypysimpleGUI - 动态创建线程
【发布时间】:2022-01-07 15:08:50
【问题描述】:

我用 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)

图片:

【问题讨论】:

    标签: loops main tk pysimplegui


    【解决方案1】:

    在您的线程中使用库 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()
    

    【讨论】:

      猜你喜欢
      • 2022-12-05
      • 2012-06-25
      • 2012-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-01
      相关资源
      最近更新 更多