python - 暂停 Jupyter Notebook 小部件,等待用户输入
问题描述
我和 TheInterestedOne在这里问的问题相同。
我需要为用户创建两个按钮,并建议用户单击循环中的两个按钮之一;以便循环的下一次迭代仅在用户选择之后发生。
我读了这个来源,但我不能让它适用于按钮。我不明白,在使用按钮的情况下,小部件属性如何变化。
from functools import wraps
def yield_for_change(widget, attribute):
def f(iterator):
@wraps(iterator)
def inner():
i = iterator()
def next_i(change):
try:
i.send(change.new)
except StopIteration as e:
widget.unobserve(next_i, attribute)
widget.observe(next_i, attribute) //**button.on_click(on_button_clicked)
may be?**
# start the generator
next(i)
return inner
return f
from ipywidgets import Button
button=Button()
def on_button_clicked():
print("Button clicked.")
@yield_for_change(button, 'value')
def f():
for i in range(10):
print('did work %s'%i)
x = yield
button.on_click(on_button_clicked)
解决方案
此版本使用awaitio
并针对按钮进行了修改。
from ipywidgets import Button
import asyncio
def wait_for_change(widget):
future = asyncio.Future()
def getvalue(change):
future.set_result(change.description)
widget.on_click(getvalue, remove=True)
# we need to free up the binding to getvalue to avoid an InvalidState error
# buttons don't support unobserve
# so use `remove=True`
widget.on_click(getvalue)
return future
button = Button(description="wow")
list_to_tag = ["one", "two", "three", "four"]
async def f():
for i in list_to_tag:
print("going to tag {}".format(i))
x = await wait_for_change(button)
print("tagged {} with {}".format(i, x))
print()
asyncio.create_task(f())
button
推荐阅读
- web-applications - 我可以使用 UML 和维度建模来设计 Web 应用程序吗?
- java - 从 python 代码 (opencv) 移植到 java (android)
- python - 在对一个数据框进行分组以生成字典后,如何将此字典转换回数据框
- android - 带有标记的 Osmdroid MapEventsReceiver 不起作用
- node.js - Mongoose 从 model.find 和 model.FindOne 响应中删除了一些数据
- python - 无法在字典中获取总和
- java - Android:IllegalArgumentException:两个视图在层次结构中具有相同的 id
- android - 需要从 Firebase 存储中获取文件的公共 URL
- java - 任何数字或 NULL 值的正则表达式
- xml - 如何将 xsl 样式表从一个 xsl 导入或包含到另一个 xsl?