python - 如何在 jupyter notebook 的选项卡式布局中延迟输出?

标签 python jupyter-notebook ipywidgets

我想使用 ipywidgets 在 jupyter notebook 中创建一个选项卡式布局。我只想在单击特定选项卡时处理它的输出。换句话说,延迟输出。

from ipywidgets import widgets

out1 = widgets.Output()
with out1:
    get_output_1()

out2 = widgets.Output()
with out2:
    get_output_2()

out = widgets.Tab([out1, out2])
out.set_title(0, 'out1')
out.set_title(1, 'out2')

display(out)

我希望函数 get_output_1()get_output_2() 仅在单击相应选项卡时被调用。

请帮帮我。

最佳答案

您可以使用observe 函数来检测哪个选项卡被选中,然后从字典中选择正确的输出小部件,运行您的函数,然后显示返回值。

您可能希望长时间运行的函数具有 @lru_cache 装饰器,这样当您在选项卡之间来回滑动时,等待时间会更短。

    from IPython.display import clear_output, display
    import time
    import ipywidgets as widgets
    from functools import lru_cache

    # set up a dictionary of Output widgets
    outputs = {i: widgets.Output() for i in range(0,3)}

    # add the Output widgets as tab childen
    tab = widgets.Tab()
    tab.children = list(outputs.values())
    for i, title in outputs.items():
        tab.set_title(i, 'Tab '+str(i))

    def print_on_select(widget):
    #     get the correct Output widget based on the index of the chosen tab
        tab_idx = widget['new']
        output_widget = outputs[tab_idx]
        with output_widget:
            clear_output()
            print('running long function')
            value = long_running_function(tab_idx)
            clear_output()
            print(value)

    @lru_cache(32)
    def long_running_function(tab_idx):
        time.sleep(2)
        return 'this is tab number ' + str(tab_idx)

    tab.observe(print_on_select, names='selected_index')

    display(tab)

关于python - 如何在 jupyter notebook 的选项卡式布局中延迟输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56949504/

相关文章:

javascript - 使用 ViewList 和 create_child_view 在 ipywidgets 中创建子部件会产生错误

python - 小部件在 Jupyter 笔记本中不起作用

python - 如何从 timedelta 中删除微秒

python - 在 Django 中检索图像

python - Jupyter 笔记本中的 Tqdm 4.28.1 "IntProgress not found. Please update jupyter and ipywidgets."

python - 如何检查是否启用了 Jupyter Notebook 扩展?

python - 在垃圾收集中调试 python 段错误

Python代码查找点和曲线之间的最小距离

python - ipython,从 bash 到变量

r - 使用带有 R 内核的 jupyter 笔记本,如何通过引用抑制更新 data.table 的打印结果?