You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PySimpleGUI自动点击器Stop按钮无法终止问题求助

解决PySimpleGUI自动点击器Stop按钮无法终止程序的问题

你的代码点击Start后,主线程被循环内的time.sleep和pyautogui操作阻塞,导致无法及时响应Stop按钮的事件。要解决这个问题,需将自动操作逻辑放到子线程中,让主线程专注处理GUI事件,同时用标志变量控制线程运行。

修改后的代码如下:

import pyautogui
import time
import PySimpleGUI as sg
import threading

# 控制线程运行的标志
running = False

def auto_operation(num_clicks, type_interval):
    global running
    time.sleep(5)
    for i in range(num_clicks):
        if not running:
            break
        pyautogui.click()
        time.sleep(10)
        if not running:
            break
        # 拆分输入过程,每输入一个字符就检查运行状态
        text = "Hello, wORLD how are you"
        for char in text:
            if not running:
                break
            pyautogui.typewrite(char, interval=5)
        if running:
            pyautogui.press('enter')
            time.sleep(type_interval)
    time.sleep(5)

def main_app():
    global running
    try:
        layout = [[sg.Text('Enter the number of clicks to perform: '), sg.InputText()],
                  [sg.Text('Enter the interval between messages (in seconds): '), sg.InputText()],
                  [sg.Button('Start'), sg.Button('Stop')]]

        window = sg.Window('Automatic Clicker', layout)

        while True:
            event, values = window.read()
            if event == 'Start':
                if not running:
                    try:
                        num_clicks = int(values[0])
                        type_interval = float(values[1])
                        running = True
                        # 启动子线程执行自动操作
                        threading.Thread(target=auto_operation, args=(num_clicks, type_interval), daemon=True).start()
                    except ValueError:
                        sg.popup_error("请输入有效的数字!")
            elif event == 'Stop' or event == sg.WINDOW_CLOSED:
                running = False
                break

    except Exception as e:
        print(f"An error occurred: {str(e)}")
    finally:
        window.close()

if __name__ == "__main__":
    main_app()

关键改动说明:

  • 引入threading模块,将自动点击、输入的逻辑封装到auto_operation函数中,作为子线程的执行目标
  • 添加全局变量running,作为控制线程是否继续运行的开关
  • 点击Start时启动子线程并设置running=True;点击Stop时设置running=False,触发线程退出
  • 在auto_operation的每一步操作前检查running状态,确保能及时响应Stop指令
  • 拆分pyautogui.typewrite的执行流程,避免因长时间输入操作无法中断
  • 增加输入合法性校验,防止非数字输入导致程序报错
  • 设置子线程为daemon=True,保证主线程退出时子线程自动终止

内容的提问来源于stack exchange,提问作者Arbaz ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 03:44:56