问题描述
我在Jupyter笔记本中有一个简单的GUI,其中包含两个小部件:带有3个选项的下拉菜单和一个按钮。
所需的行为是:
- 执行包含小部件的单元格(请参见下面的代码)
- (只要需要)等待用户单击按钮
- 打印下拉菜单的值(用户选择)
我用asyncio
尝试了两个选项,但是都没有提供期望的结果。
from ipywidgets import Button,Dropdown,HBox
import asyncio
choices = Dropdown(options=[1,2,3],description='Choice')
button = Button(description="Select")
panel = HBox([choices,button])
def wait_for_change(push_button,dropdown):
future = asyncio.Future() # Make getvalue function awaitable
def getvalue(change):
future.set_result(dropdown.value)
push_button.on_click(getvalue,remove=True) # Unbind function from widget
push_button.on_click(getvalue)
return future
async def main():
user_choice = await wait_for_change(button,choices)
print(f"User selected option {user_choice}")
return user_choice
display(panel)
print("Which option would you like to chose?")
"""OPTION 1: non blocking but push button works"""
out = asyncio.create_task(main())
"""OPTION 2: blocking but push button has no effect"""
# out = await main()
print("End of code")
选项1
使用选项1执行单元格时,执行将直接进行到最后一行,而out = asyncio.create_task(main())
不会阻止它。因此,在单元执行完成之前,我无法获得用户的选择。
out.result()
提供了预期的结果,但是在单元运行完成之前无法检索:必须在下一个单元中调用它。
选项2
如果将out = asyncio.create_task(main())
替换为out = await main()
,则在out = await main()
上成功阻止了单元格的执行,但是按下按钮无效。执行挂起。
我想念什么?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)