问题
I'm trying to do something in a Jupyter notebook that runs a continuous process, but with a pause button to interrupt it. Below is a simplified version of what I've done so far, but it seems Ipython wants to complete the entire run() function before it executes commands it receives from the button. The problem, of course, being that run() will never finish unless interrupted.
Interestingly, the below strategy works just fine in my Tkinter frontend so long as I put a pause(0.0001) at the end of the updateGraph() function. Architecturally, I'd be curious why Tkinter is willing to listen to input events during that pause but Jupyter isn't. But more importantly, is there a way to get Jupyter to listen while running run()?
from ipywidgets import Button
from IPython.display import display
startstop = Button(description='Run')
startstop.click = run
display(startstop)
def run(b=None):
running=True
while running:
#Do stuff and update display
updateGraph()
startstop.click = pause
startstop.description = 'Pause'
def pause(b=None):
running = False
startstop.click = run
startstop.description = 'Run'
回答1:
I prefer using Keyboard for this purpose. It is a much simpler approach to the same problem...
import keyboard
def run():
running=True
while running:
pass # some code here...
if keyboard.is_pressed('alt'):
break
run()
Press Alt key anytime to stop the execution of the program.
来源:https://stackoverflow.com/questions/62704909/getting-a-jupyter-notebook-to-listen-to-input-events-while-running-a-continuous