【发布时间】:2020-01-08 00:45:16
【问题描述】:
在下面的代码中,我想要以下行为:
当用户单击我在应用程序模式中定义的按钮时,我希望调用其中的 print_async 例程,该例程等待 2 秒,然后打印“”这是来自 buttonCLicked 的异步打印“,然后我想要之后的打印是“按钮单击!”出现。相反,我得到的是解释器错误:
任何帮助表示赞赏。
文件“cell_name”,第 6 行 SyntaxError: 'await' 在异步函数之外
from IPython.display import display
from ipywidgets import widgets
import asyncio
#DO NOT CHANGE THIS CELL
#Define an async function
async def print_async(message):
await asyncio.sleep(2)
print(message)
# Show that we can print from the top-level jupyter terminal
await print_async("This is a top-level async print")
#Define a callback function for the button
def onButtonClicked(_):
await print_async("this is async print from buttonCLicked")
print("button clicked!")
button = widgets.Button(
description='Click me',
disabled=False,
button_style='', # 'success', 'info', 'warning', 'danger' or ''
tooltip='Click me',
icon=''
)
button.on_click(onButtonClicked)
display(button)
button = widgets.Button(
description='Click me',
disabled=False,
button_style='', # 'success', 'info', 'warning', 'danger' or ''
tooltip='Click me',
icon=''
)
button.on_click(onButtonClicked)
display(button)
Goal: Get the button click to call the print_async method
【问题讨论】:
标签: jupyter-notebook python-asyncio