退出 ipywidgets 交互/交互以在 jupyter notebook 中产生最终输出

Exiting ipywidgets interact / interactive to produce a final output in jupyter notebook

我想用 %matplotlib notebook 魔术来类比 matplotlib 情节。它在右上角有一个 "power button" - 单击它后, UI 消失,输出变成最终视图的 PNG。

假设我有一个函数可以使用来自 int 滑块的值来过滤数据帧:

from ipywidgets import interact
# df = pd.read_csv('...')

@interact(zone=(-1, 12))
def show(zone):
    if zone > 0:
        return df[df.ZoneId == zone]  # show filtered results

    if zone == 0:
        return df  # show all results

    # HERE: I want to exit the interaction, and make the int slider disappear, and the whole
    # of df to become the rendered output

我已经尝试创建滑块并将其绑定到某物:

zone_slider = IntSlider(0, -1, 12)
@interact(zone=zone_slider)
def show(zone):
    # ...
    zone_slider.close()  # slider disappears, but output is still the same `interactive`.

我希望输出与笔记本一起保存,并且(在关闭笔记本并使用新内核打开它之后)无需 运行 任何代码(也不执行相互作用)。现在它只显示为 intearctive(children=[IntSlider(...), Output(...)], ...).

我想要一个通用的解决方案(完成任何交互,例如当 Checkbox 变成 True 时)。我不确定是否可以不求助于较低级别的 ipywidgets.interactive 函数或 interact_manual,但我不知道如何使用它们。

1 - 如何以编程方式删除 UI 并仅保留输出

您可以使 适应 hide/show 小部件。在 code_toggle 函数上,您可以添加如下代码:

$('div.widget-slider').hide();

您必须为您使用的每种类型的小部件执行此操作。也不要忘记添加 .show()

2 - 如何在保存的笔记本上保留交互式输出,而不是 'interactive(children...'

我找到了一个更具体的问题,但没有回答,我回答了它 here。基本上,从菜单项 WidgetsSave Notebook Widget State.

调用操作是一种 hack