代码之家  ›  专栏  ›  技术社区  ›  siledi

如何在Jupyter笔记本中暂停此代码?

  •  0
  • siledi  · 技术社区  · 2 年前

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

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

    我该怎么做?

    1 回复  |  直到 2 年前
        1
  •  0
  •   Ahmed AEK    2 年前

    要做到这一点,一个简单的技巧是(不要执行会滥用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循环之前已完全执行。