【发布时间】:2020-10-09 14:46:31
【问题描述】:
让我们假设以下问题:我们有一个 Ipywidget 按钮和一个进度条。单击该按钮时,将执行一个函数 work(),该函数仅填充进度条直到完成,然后反转该过程并将其清空。就目前而言,这样的功能会持续运行。以下代码sn -p提供了对应的MWE:
# importing packages.
from IPython.display import display
import ipywidgets as widgets
import time
import functools
# setting 'progress', 'start_button' and 'Hbox' variables.
progress = widgets.FloatProgress(value=0.0, min=0.0, max=1.0)
start_button = widgets.Button(description="start fill")
Hbox = widgets.HBox(children=[start_button, progress])
# defining 'on_button_clicked_start()' function; executes 'work()' function.
def on_button_clicked_start(b, start_button, progress):
work(progress)
# call to 'on_button_clicked_start()' function when clicking the button.
start_button.on_click(functools.partial(on_button_clicked_start, start_button=start_button, progress=progress))
# defining 'work()' function.
def work(progress):
total = 100
i = 0
# while roop for continuous run.
while True:
# while loop for filling the progress bar.
while progress.value < 1.0:
time.sleep(0.01)
i += 1
progress.value = float(i)/total
# while loop for emptying the progress bar.
while progress.value > 0.0:
time.sleep(0.01)
i -= 1
progress.value = float(i)/total
# display statement.
display(Hbox)
目的是包括“停止”和“恢复”按钮,以便在单击第一个时中断 while 循环,并在按下第二个时恢复执行。这可以在不使用线程、多处理或异步的情况下完成吗?
【问题讨论】:
标签: python while-loop jupyter-notebook ipywidgets