尝试使用 PySimpleGUI 退出 While True 循环

Trying to Exit a While True Loop using PySimpleGUI

这是我的代码:

Main.py:

import PySimpleGUI as sg
import Config
import threading


def main():
    layout = [  [sg.Text('Real Time Raspberry Pi Sniffer')],
            [sg.Button('Run While Loop'), sg.Button('Exit')],     # a couple of buttons
            [sg.Output(size=(60,15))] ]         # an output area where all print output will go
            #[sg.Input(key='_IN_')] ]             # input field where you'll type command

    window = sg.Window('Realtime Shell Command Output', layout)

    while True:            # Event Loop
        event, values = window.Read()
        if event == 'Run While Loop':             
            t1 = threading.Thread(target = Config.whileLoop())
            t1.start()
        elif event == 'Exit' or event == WIN_CLOSED:
            print('CLICKED EXIT') 
            window.Close()

if __name__ == '__main__':
    main()

Config.py

from PySimpleGUI.PySimpleGUI import WIN_CLOSED
def whileLoop():
    state = True
    while (state == True):          
        print("It works!")  

我正在尝试创建 GUI window,它会在用户单击按钮时运行一个 while 循环(在这种情况下,当他们单击“运行 While Loop”时)。但是,我遇到了一个问题,因为我的代码卡在了 Config.py 中的嵌套 while 循环中。我希望代码能够退出 while 循环并在单击 'Exit' 按钮时由程序停止。我查看了 Threading,但不确定还能做什么。有什么帮助,谢谢!

这是一个猜测,因为我之前没有做过你正在尝试的事情。

也许如果你把你的config.py改成这样:

state=True
def whileLoop():
   while (state == True):          
       print("It works!") 

(使状态成为模块全局标志)

并像这样修改你的事件循环:

while True:            # Event Loop
    event, values = window.Read()
    if event == 'Run While Loop':             
        t1 = threading.Thread(target = Config.whileLoop())
        t1.start()
    elif event == 'Exit' or event == WIN_CLOSED:
        print('CLICKED EXIT') 
        Config.state = False # set the exit flag
        t1.join() # I'm not sure about this, could try without
        window.Close()

同样,我已经使用 Python 很长时间了,但从来没有像这样。

我导入 Config.py 中定义的 class Func,然后调用实例 Func() 的方法 while_loop。为 while 循环设置标志 True 或 False 是否保持 运行。

示例代码

# Config.py

from time import sleep
from PySimpleGUI import WIN_CLOSED


class Func():

    def __init__(self):
        self.state = False
        self.count = 0

    def while_loop(self, window):
        while self.state:
            sleep(0.5)                                      # Simulate job done here
            self.count += 1
            window.write_event_value("Done", self.count)    # update GUI by event
# main.py

from time import sleep
from threading import Thread
import PySimpleGUI as sg
import Config


def main():

    layout = [
        [sg.Text('Real Time Raspberry Pi Sniffer')],
        [sg.Button('Start'), sg.Button('Stop'), sg.Button('Exit')],
        [sg.StatusBar('', size=60, key='Status')],
    ]
    window = sg.Window('Realtime Shell Command Output', layout, enable_close_attempted_event=True)
    status = window['Status']
    func = Config.Func()
    thread = None
    while True:

        event, values = window.read()

        if event in (sg.WINDOW_CLOSE_ATTEMPTED_EVENT, 'Exit'):
            func.state = False
            sleep(0.5)  # Wait thread to stop
            break
        elif event == 'Start' and thread is None:
            func.state = True
            func.count = 0
            thread = Thread(target=func.while_loop, args=(window,), daemon=True)
            thread.start()
        elif event == 'Stop':
            func.state = False
            thread = None
        elif event == 'Done':
            count = values[event]
            status.update(f"Job done at #{count:0>3}")

    window.Close()

if __name__ == '__main__':
    main()