How to lazify output in Tabbed Layout in jupyter notebook?

百般思念 提交于 2019-12-24 09:59:43

问题


I want to create a tabbed layout in jupyter notebook using ipywidgets. I want to process the output of a particular tab only when it is clicked. In other words, lazify the output.

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)

I want the functions get_output_1() and get_output_2() to be called only when the corresponding tab is clicked.

Please help me out.


回答1:


You can use the observe function to detect which tab is being selected, and then choose the correct Output widget from a dictionary, run your function and then display the return value.

You might want your long running function to have the @lru_cache decorator so that as you flick backwards and forward between tabs you have a shorter wait time.

    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)


来源:https://stackoverflow.com/questions/56949504/how-to-lazify-output-in-tabbed-layout-in-jupyter-notebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!