连续的ipywidgets按钮 [英] Successive ipywidgets buttons

查看:127
本文介绍了连续的ipywidgets按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to make a successive process of buttons clicks using ipywidgets buttons.

单击按钮1可以清除按钮1并显示按钮2等等...

Click on button 1 is supposed to clear button 1 and display button 2 etc...

看起来,等待变量的引入使我的清除函数无法访问,而且我不明白为什么.

It looks like the introduction of the wait variable make my purge function unreachable, and I don't understand why.

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循环是一个非常紧密的循环,可能会使CPU内核旋转100%.这不仅会使您的程序陷入瘫痪,甚至可能使您的整个计算机陷入瘫痪.

Your while wait: pass loop is an extremely tight loop that will likely spin a CPU core at 100%. This will bog down not just your program but perhaps even your entire computer.

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

I think what you want to do is to display the next button not in the for loop, but in the on_click callback.

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,以便在它们到达最后一个按钮时执行其他操作.

Then you can put an if i == 5 in your function to do something else when they reach the last button.

这篇关于连续的ipywidgets按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆