【问题标题】:Successive ipywidgets buttons连续的 ipywidgets 按钮
【发布时间】:2020-05-31 09:05:30
【问题描述】:

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

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

看起来等待变量的引入使我的清除功能无法访问,我不明白为什么。

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

【问题讨论】:

    标签: python button jupyter-notebook ipywidgets


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答,我认为您解决了部分问题,但按钮仍然被阻止。未达到吹扫功能。代码在逻辑上看起来很准确,所以我认为这个错误与我对 ipywidgets 库的使用有关。
    【解决方案2】:

    虽然可能不是最干净的,但这是我的解决方案。

    按钮和其他 ipywidgets 的属性是动态可修改的:

    import ipywidgets as widgets
    from IPython.display import display
    from IPython.display import clear_output
    
    # Create and display button
    button = widgets.Button(description="Begin")
    output = widgets.Output()
    display(button, output)
    
    # Initialize variable
    i = 0
    
    def update_button(args):
        global i  # Declare i as a global variable
        with output:
            print("Button %s clicked." % i)
           
            # Button attributes' change conditions
            if i<2:
                button.description = 'Next'
            else:
                button.description = 'Done'
                button.button_style='success'
                button.icon='check'
            
            # Do something different on each button press
            if i == 0:
                # Do stuff
                print('Doing stuff')
            elif i == 1:
                # Do other stuff
                print('Doing other stuff')
            elif i ==2:
                # Do some other stuff
                print('Doing some other stuff and finishing')
            i=i+1
            clear_output(wait=True)
    
    button.on_click(update_button)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      • 2017-07-22
      • 1970-01-01
      • 2019-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多