python - 连续的 ipywidgets 按钮

标签 python button jupyter-notebook ipywidgets

我正在尝试使用 ipywidgets 按钮进行连续的按钮点击过程。

点击按钮 1 应该清除按钮 1 并显示按钮 2 等...

看起来wait变量的引入让我的purge函数无法访问,我不明白为什么。

from ipywidgets import Button
from IPython.display import display, clear_output

def purge(sender):
    print('purge')
    clear_output()
    wait=False

for i in range(5):
    print(f'Button number :{i}')
    btn = widgets.Button(description=f'Done', disabled=False,
                        button_style='success', icon='check')
    btn.on_click(purge)
    display(btn)
    wait=True
    while wait:
        pass

最佳答案

您的 while wait: pass 循环是一个非常紧凑的循环,可能会以 100% 的速度旋转 CPU 核心。这不仅会使您的程序陷入困境,甚至可能使您的整个计算机陷入困境。

我认为您想做的是不在 for 循环中而是在 on_click 回调中显示下一个按钮。

from ipywidgets import Button
from IPython.display import display, clear_output

def purge(i):
    print(f'Button number :{i}')
    clear_output()
    btn = widgets.Button(description=f'Done', disabled=False,
                        button_style='success', icon='check')
    btn.on_click(purge, i + 1)
    display(btn)

purge(1)

然后你可以在你的函数中放置一个 if i == 5 来在他们到达最后一个按钮时做其他事情。

关于python - 连续的 ipywidgets 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62113899/

相关文章:

python - Python 中的参数解析(必需与可选)

python - 如何使用 Python 的 Xlib 将文本写入根窗口?

button - 使用 JavaFX 2.2 助记符(和加速器)

javascript - 如何启用和禁用按钮

python - 无法从 anaconda 运行 jupyter 笔记本,但可以从 python 运行

jupyter-notebook - 使用 jupyterthemes 和目录修复 jupyter notebook 工具栏

python - 导入 Tensorflow 时 Jupyter Notebook 内核死机

Python研究

javascript - 如何激活:focus on the input+button when a user click into the input?

python - SQL Server 与 AWS GLUE Python 3 作业的连接