【问题标题】:How to create a toogle button to show and clear output using ipywidgets?如何使用 ipywidgets 创建一个切换按钮来显示和清除输出?
【发布时间】:2019-06-20 15:26:06
【问题描述】:

我想创建一个切换按钮来显示一些输出并在使用 ipywidget 在 jupyter notebook 中切换时清除它。

我尝试使用widgets.Output() 来实现。然而,当我点击的次数越来越多时,这会显示空行。

请帮帮我。

import ipywidgets as w
toggle = w.ToggleButton(description='click me')

out = w.Output()

def fun(obj):
    global out
    with out:
        display('asd')
    if obj['new']:  
        display(out)
    else:
        out.clear_output()
        out = w.Output()

toggle.observe(fun, 'value')
display(toggle)

【问题讨论】:

    标签: python jupyter-notebook ipywidgets


    【解决方案1】:

    我认为global 关键字与display(out) 的组合导致了这里的问题。我在下面做了一点简化:

    在代码主体中显示output 小部件,并使用clear_output 命令(输出小部件仍然“可见”但高度为零)。

        import ipywidgets as w
        toggle = w.ToggleButton(description='click me')
    
        out = w.Output(layout=w.Layout(border = '1px solid black'))
    
        def fun(obj):
            with out:
                if obj['new']:  
                    display('asd')
                else:
                    out.clear_output()
    
        toggle.observe(fun, 'value')
        display(toggle)
        display(out)
    

    【讨论】:

    • (输出小部件仍然“可见”,但高度为零)您能解释一下吗?虽然它工作正常,但我只想知道你到底是什么意思?非常感谢。
    • 查看我编辑的带有边框的版本,以说明输出小部件会发生什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2014-06-02
    • 2010-09-23
    • 2016-04-04
    • 1970-01-01
    • 2021-05-15
    相关资源
    最近更新 更多