阻止执行,直到用户单击Jupyter小部件

问题描述

我在Jupyter笔记本中有一个简单的GUI,其中包含两个小部件:带有3个选项的下拉菜单和一个按钮。

Output

所需的行为是:

  1. 执行包含小部件的单元格(请参见下面的代码)
  2. (只要需要)等待用户单击按钮
  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 (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...