PySampleGUI 多线程

线程通过window.write_event_value 写入事件并传递参数。

点击Go运行读秒,可多次点击同时运行多个线程。

import PySimpleGUI as sg
import threading
import time
import random


def wait_thread(window, name):
    for i in range(100):
        window.write_event_value('-ODD-', i)
        print('thread {} | num: {}'.format(''.join(name), i))
        time.sleep(1)
    window.write_event_value('-FINISH-', 'thread {} finished'.format(name))

def wait(name):
    threading.Thread(target=wait_thread, args=(window, name), daemon=True).start()

layout = [[sg.Output(size=(60, 20))],
          [sg.Button('Go'), sg.Button('Nothing'), sg.Exit()]]

window = sg.Window('', layout)

while True:
    event, values = window.read()
    if event in [sg.WIN_CLOSED, 'Exit']:
        break

    elif event == 'Go':
        name = random.choices('abcdefghijklmnopqrstuvwxyz', k=6)
        wait(name)
    elif event == 'Nothing':
        print('Nothing')

window.close()