如何创建一个 toogle 按钮来使用 ipywidgets 显示和清除输出



我想创建一个切换按钮来显示一些输出,并在使用 Jupyter 笔记本中切换时清除它 ipywidget .

我尝试使用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)

我认为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)

最新更新