在不关闭GUI窗口的情况下停止线程

时间:2020-04-10 20:41:47

标签: python multithreading pysimplegui

我正在独自学习python,据我了解,我的水平可能不是一个“脚本小子”的可怜借口,并且最终最终会借用并混搭不同的脚本,直到达到我想要的为止。但是,这是我第一次尝试为我拥有的一个脚本创建GUI。我正在使用PySimpleGUI,并且已经能够很好地理解它。除了一件事情,其他所有东西都按照我想要的方式工作。

问题是我想在不退出GUI的情况下停止正在运行的守护程序线程。如果我使停止按钮起作用,则GUI关闭,而如果GUI没有关闭,则不会停止线程。问题出在'64 -68'行之间。我已经尝试了一些方法,只是将占位符放在“ 65”行上,以记住我试图保持GUI(在我的头脑中为“主线程”)运行。脚本将在此状态下运行,但“停止”按钮不起作用。

注意:我在脚本中添加了很多注释,因此我记得每个部分是什么,它的作用以及需要清除的内容。如果我打算共享脚本,我不知道这是否是一个好习惯。另外,如果有关系,我可以使用Visual Studio Code。

#!/usr/local/bin/python3

import PySimpleGUI as sg
import pyautogui
import queue
import threading
import time
import sys
from datetime import datetime
from idlelib import window

pyautogui.FAILSAFE = False
numMin = None

# ------------------ Thread ---------------------

def move_cursor(gui_queue):
    if ((len(sys.argv)<2) or sys.argv[1].isalpha() or int(sys.argv[1])<1):
        numMin = 3
    else:
        numMin = int(sys.argv[1])
    while(True):
        x=0
        while(x<numMin):
            time.sleep(5)                   # Set short for debugging (will set to '60' later)
            x+=1
        for i in range(0,50):
            pyautogui.moveTo(0,i*4)
        pyautogui.moveTo(1,1)
        for i in range(0,3):
            pyautogui.press("shift")
        print("Movement made at {}".format(datetime.now().time()))  

# --------------------- GUI ---------------------

def the_gui():
    sg.theme('LightGrey1')                  # Add a touch of color
    gui_queue = queue.Queue()               # Used to communicate between GUI and thread


    layout = [  [sg.Text('Execution Log')],
             [sg.Output(size=(30, 6))],
             [sg.Button('Start'), sg.Button('Stop'), sg.Button('Click Me'), sg.Button('Close')]  ]
    window = sg.Window('Stay Available', layout)

# -------------- EVENT LOOP ---------------------
    # Event Loop to process "events"

    while True:
        event, values = window.read(timeout=100)
        if event in (None,'Close'):
          break
        elif event.startswith('Start'):     # Start button event
            try:
                print('Starting "Stay Available" app')
                threading.Thread(target=move_cursor,
                                 args=(gui_queue,), daemon=True).start()
            except queue.Empty:
                print('App did not run')
        elif event.startswith('Stop'):      # Stop button event
            try:
                print('Stopping "Stay Available" app')
                threading.main_thread       # To remind me I want to go back to the original state
            except queue.Empty:
                print('App did not stop')
        elif event == 'Click Me':           # To see if GUI is responding (will be removed later)
            print('Your GUI is alive and well')

    window.close(); del window

if __name__ == '__main__':
    gui_queue = queue.Queue()               # Not sure if it goes here or where it is above
    the_gui()
    print('Exiting Program')

0 个答案:

没有答案