在Ipywidgets中为持续循环添加停止/恢复按钮(无需多线程等)
Absolutely! You can implement stop/resume functionality by using a simple flag variable to control the execution flow of your loops. Since we're working in a synchronous context, we just need to check this flag at regular intervals within the work function to pause or resume progress.
Key Changes:
- Add a boolean flag
is_runningto track whether the progress bar should be updating - Modify the
work()function to check this flag before each progress update; if paused, wait in a low-impact loop until the flag is re-enabled - Add Stop and Resume buttons, with callbacks to toggle the
is_runningflag
Full Modified Code
from IPython.display import display import ipywidgets as widgets import time import functools # Control flag to manage execution state is_running = True # Create widgets progress = widgets.FloatProgress(value=0.0, min=0.0, max=1.0) start_button = widgets.Button(description="Start Fill") stop_button = widgets.Button(description="Stop", button_style="danger") resume_button = widgets.Button(description="Resume", button_style="success") Hbox = widgets.HBox(children=[start_button, stop_button, resume_button, progress]) def on_button_clicked_start(b, progress): global is_running is_running = True work(progress) def on_button_clicked_stop(b): global is_running is_running = False def on_button_clicked_resume(b): global is_running is_running = True # Bind button callbacks start_button.on_click(functools.partial(on_button_clicked_start, progress=progress)) stop_button.on_click(on_button_clicked_stop) resume_button.on_click(on_button_clicked_resume) def work(progress): total = 100 i = 0 while True: # Fill progress bar while progress.value < 1.0 and is_running: time.sleep(0.01) i += 1 progress.value = float(i)/total # Wait if paused mid-fill while not is_running: time.sleep(0.01) # Empty progress bar while progress.value > 0.0 and is_running: time.sleep(0.01) i -= 1 progress.value = float(i)/total # Wait if paused mid-empty while not is_running: time.sleep(0.01) display(Hbox)
How It Works:
- The
is_runningflag acts as a toggle: when set toFalse, the work function pauses its progress updates and waits in a low-impact loop (with smalltime.sleep()calls to avoid hogging resources) - Clicking "Stop" sets
is_runningtoFalse, which triggers the waiting loop in the current progress stage - Clicking "Resume" sets
is_runningback toTrue, allowing the progress bar to continue from where it left off - The "Start" button re-enables the flag and starts the cycle if it was stopped
This approach keeps everything in a single synchronous thread, avoiding the complexity of concurrency while still giving you full control over the progress execution.
内容的提问来源于stack exchange,提问作者AZarketa
相关产品推荐
相关产品推荐

