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

如何在PySimpleGUI中点击后禁用Start update按钮?附代码求助

Prevent Duplicate Clicks on PySimpleGUI's "Start Update" Button

Got it, let's fix that duplicate click problem for your updater app. The key is to disable the button as soon as it's clicked, then re-enable it once the task finishes or the user cancels the process. We'll also make sure the window stays responsive while the task runs.

Here's your modified code:

import PySimpleGUI as sg
import time

mylist = ["task 1", "task 2", "task 3", "task 4"]
progressbar = [[sg.ProgressBar(len(mylist), orientation='h', size=(51, 10), key='progressbar')]]
outputwin = [[sg.Output(size=(78,20))]]
layout = [
    [sg.Frame('Progress', layout=progressbar)],
    [sg.Frame('Output', layout=outputwin)],
    [sg.Submit('Start update'), sg.Cancel()]
]
window = sg.Window('Assistant updater', layout)
progress_bar = window['progressbar']

while True:
    event, values = window.read(timeout=10)
    if event == 'Cancel' or event is None:
        break
    elif event == 'Start update':
        # Disable the button immediately to prevent duplicate clicks
        window['Start update'].update(disabled=True)
        
        for i, item in enumerate(mylist):
            print(item)
            if item == "task 2":  # Adjust this condition to match your actual use case
                print('New line started')
            time.sleep(1)
            progress_bar.UpdateBar(i + 1)
            
            # Check for Cancel event during the task to keep window responsive
            event, values = window.read(timeout=10)
            if event == 'Cancel' or event is None:
                break
        
        # Re-enable the button once task is done or canceled
        window['Start update'].update(disabled=False)

window.close()

Key Changes Explained:

  • Disable on click: Right when the "Start update" event triggers, we use window['Start update'].update(disabled=True) to gray out the button so it can't be clicked again mid-task.
  • Keep window responsive: Inside the task loop, we add a window.read(timeout=10) call. This lets the app check for the Cancel event (or window close) while the task runs, so the window doesn't freeze up.
  • Re-enable after task: No matter if the task finishes normally or gets canceled, we re-enable the button at the end so the user can run the task again if needed.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 15:02:31