The*_*One 6 python asynchronous button jupyter-notebook ipywidgets
在我的笔记本中,我有一个循环,我想在其中要求用户二进制“是”或“否”。在这个选择上,算法应该继续。
for i in range(n_total):
display.clear_output(wait=True)
waiting_for_scoring = True
print("True or False?")
display.display(widgets.HBox((true_button, false_button)))
a = true_button.on_click(on_true_button)
a = false_button.on_click(on_false_button)
while waiting_for_scoring == True:
#waiting for user input
pass
Run Code Online (Sandbox Code Playgroud)
在小部件 HBox 创建之后,如何使循环等待,并等待用户输入(单击按钮)以继续回答新值?
这是我对按钮的两个功能:
def on_true_button(x):
global waiting_for_scoring
print('NO!!!!')
y_new = 1
waiting_for_scoring = False
return y_new
def on_false_button(x):
global waiting_for_scoring
print('YES')
y_new = 0
waiting_for_scoring = False
return y_new
Run Code Online (Sandbox Code Playgroud)
你能帮我停止循环直到用户按下按钮然后使用这个输入吗?先感谢您
有一个名为jupyter-ui-poll 的简洁小库,它可以准确处理这个用例!您拥有的其余按钮设置可以保持不变。我们只需要在循环周围包装一个可轮询范围,如下所示:
from jupyter_ui_poll import ui_events
...
with ui_events() as poll:
while waiting_for_scoring == True:
#waiting for user input
poll(10) # poll queued UI events including button
pass
Run Code Online (Sandbox Code Playgroud)
您可能还想time.sleep(...)在循环中添加 a 以避免过多旋转。
问题在于 IPython 内核执行事件队列,但只有一个队列用于 UI 事件回调和单元格执行。因此,一旦它忙于处理单元格,UI 事件就不会得到处理。jupyter-ui-poll暂时(在范围内)调整此排队行为以允许显式轮询。