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

How can i pause this code in 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:\Users\asd\Desktop\asd.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**

我该怎么做?

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

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.

Edit:您可能希望将 answer_pressed = True 移动到函数的末尾而不是开头,这样您就可以确定该函数之前已完全执行打破 while 循环。