Rick Cromer
Rick Cromer

Reputation: 33

Passing updated information from PySimpleGUI to an actively running thread

I have a long running process that I've been running from the command line. It runs through the entire stock market trading session. What I would like to do, is to create a UI using PySimpleGUI that I can use to change some of the controlling parameters of my long running thread, without stopping and restarting that thread. I've seen examples of updating UI from the thread, but not sending updates to the thread once it's running. I'll start with the example of an easy PySimpleGUI application for discussion sake.

import threading
import PySimpleGUI as sg
import time


def long_running_task(thread_event, update_event, window):
    while not thread_event.is_set():
        # Perform long-running task
        time.sleep(1)

        # Check for updates from GUI
        if update_event.is_set():
            update_event.clear()
            new_text = window.read(timeout=0)[1]['-INPUT-']
            print(f"Received update from GUI: {new_text}")

    print("Thread exiting")


def main():
    sg.theme('LightGrey1')

    layout = [
        [sg.Button('Start Thread'), sg.Button('Update'), sg.Button('Stop Thread')],
        [sg.InputText(key='-INPUT-')],
        [sg.Output(size=(50, 10))]
    ]

    window = sg.Window('Long Running Thread Example', layout)

    thread_event = threading.Event()
    update_event = threading.Event()

    thread = None

    while True:
        event, values = window.read(timeout=100)

        if event in (sg.WINDOW_CLOSED, 'Exit'):
            break

        if event == 'Start Thread':
            if not thread or not thread.is_alive():
                thread_event.clear()
                update_event.clear()
                thread = threading.Thread(target=long_running_task, args=(thread_event, update_event, window))
                thread.start()
                print("Thread started")

        elif event == 'Stop Thread':
            if thread and thread.is_alive():
                thread_event.set()
                thread.join()
                print("Thread stopped")

        elif event == '-INPUT-':
            update_event.set()

    window.close()


if __name__ == '__main__':
    main()

I added an update button, hoping that when I click that, it will send updated information from the input box. I can't tell if that doesn't anything.

Upvotes: 0

Views: 46

Answers (0)

Related Questions