简体   繁体   中英

How can i pause this code in Jupyter Notebook?

When i click the Submit answer button, additional codes can only be run after that.

import ipywidgets as widgets

Here are a few lines of code that are responsible for the look of the button etc.

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**

How can i do that?

a simple trick to do that (without doing an empty while loop that will abuse your cpu) is to put your code in a sleep loop untill the button is pressed.

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 : you might want to move the answer_pressed = True to the end of the function instead of the beginning, so you will be sure the function has executed fully before breaking the while loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM