簡體   English   中英

如何在 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.

編輯:您可能希望將answer_pressed = True移動到函數的末尾而不是開頭,因此您將確保函數在中斷 while 循環之前已完全執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM