如何通过 Jupyter 笔记本中的选项布局简化输出?

2024-05-23 20:07:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()只在单击相应的选项卡时被调用。在

请帮帮我。在


Tags: outputgettitlewith笔记本jupyter布局widgets
1条回答
网友
1楼 · 发布于 2024-05-23 20:07:33

您可以使用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)

相关问题 更多 >