我如何在Jupyter Notebook中暂停此代码?



当我点击提交答案按钮时,其他代码只能在此之后运行

import ipywidgets as widgets

这里有几行代码,负责按钮的外观等。

selector = widgets.RadioButtons(
options=['Valid', 'Invalid', 'Skip'], 
value=None,
description='',
disabled=False
)
button = widgets.Button(
description='Submit answer',
disabled=False,
button_style='',
)

def evaluate(button):
selection = selector.get_interact_value()    
if (selection == 'Valid'):
f = open(r"C:UsersasdDesktopasd.txt", "a", encoding='utf-8')
f.write('asd')
f.close()
elif (selection == 'Invalid'):
pass
elif (selection == 'Skip'):
pass
button.on_click(evaluate)        
left_box = widgets.VBox([selector, button])
widgets.HBox([left_box])
print('nvm') **#If I click Submit answer button, then run this code**

我该怎么做呢?

一个简单的技巧(不做一个空的while循环,会滥用你的cpu)是把你的代码在睡眠循环,直到按钮被按下。

answer_pressed = False
def evaluate(button):
global answer_pressed 
answer_pressed = True
# rest of function here
button.on_click(evaluate)        
import time
while answer_pressed == False: # put the interpreter to sleep until the button is pressed.
time.sleep(0.01) # or 0.1 depending on the required resposivity.

编辑:您可能希望将answer_pressed = True移动到函数的末尾而不是开始,这样您将确保函数在中断while循环之前已经完全执行。

相关内容

  • 没有找到相关文章

最新更新