让Jupyter笔记本在运行连续进程时侦听输入事件?

2024-09-25 08:25:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Jupyter笔记本上做一些事情,它运行一个连续的过程,但有一个暂停按钮来中断它。下面是我到目前为止所做工作的简化版本,但似乎Ipython希望在执行从按钮接收到的命令之前完成整个run()函数。当然,问题是run()永远不会结束,除非中断

有趣的是,只要我在updateGraph()函数的末尾放一个pause(0.0001),下面的策略在我的Tkinter前端就可以正常工作。在架构上,我很好奇为什么Tkinter愿意在暂停期间听输入事件,而Jupyter却不愿意。但更重要的是,有没有办法让Jupyter在运行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'

Tags: 函数runfromimporttkinterdisplayjupyterbutton
1条回答
网友
1楼 · 发布于 2024-09-25 08:25:50

为此,我更喜欢使用Keyboard。对于同样的问题,这是一种更简单的方法

import keyboard

def run():
    running=True
    while running:
        pass # some code here...
        if keyboard.is_pressed('alt'):
            break

run()

随时按Alt键停止程序的执行

相关问题 更多 >