如何隐藏代码并重新运行 jupyter 笔记本中的所有单元格?

我想在 Jupyter Notebook 的开头添加某种功能,以隐藏/显示所有单元格并重新运行所有单元格。我想要结束的是一组图表,当所有单元格重新运行时会刷新这些图表。


详细信息和我尝试过的内容:

文章IPython - 从小部件运行下面的所有单元格显示了如何添加按钮以重新运行下面的所有单元格。以及如何从使用 nbviewer 可视化的 ipython notebook 中的单元格隐藏代码?. 通过在两个不同的单元格中进行此设置,我最终得到了以下结果:

http://img4.mukewang.com/6181031e00019b6509150616.jpg

当单元格折叠时,它看起来像这样:

http://img2.mukewang.com/618103270001d5c909030100.jpg

这很好用,但我真的很好奇是否可以设置按钮的格式以使它们看起来相同。也许可以将它们对齐为同一单元格的输出?我试图通过将两个片段放在同一个单元格中来做到这一点,但现在似乎Hide button被覆盖了Refresh button:


片段 1:


from IPython.display import HTML


HTML('''<script>

  function code_toggle() {

    if (code_shown){

      $('div.input').hide('500');

      $('#toggleButton').val('Show code')

    } else {

      $('div.input').show('500');

      $('#toggleButton').val('Hide code')

    }

    code_shown = !code_shown

  }


  $( document ).ready(function(){

    code_shown=false;

    $('div.input').hide()

  });

</script>

<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show code"></form>''')


from IPython.display import Javascript, display

from ipywidgets import widgets


def run_all(ev):

    display(Javascript('IPython.notebook.execute_cells_below()'))


button = widgets.Button(description="Refresh")

button.on_click(run_all)

display(button)

现在我得到了这个:


输出 1:

http://img1.mukewang.com/6181033800011b3e09150558.jpg

有谁知道如何使它更优雅一点?


哔哔one
浏览 184回答 1
1回答

偶然的你

我真的希望有人能够提供更好的答案,但是尝试并失败了几个小时后,我发现了这一点:通过简单地混合问题中两个片段的几个部分,我可以设置Refresh button与以下格式相同的格式Hide Code buttion:输出/笔记本视图:但这仍然需要两个不同单元格中的两个代码片段,以及第三个单元格中的一些测试代码:单元格/片段1:from IPython.display import HTMLHTML('''<script>&nbsp; function code_toggle() {&nbsp; &nbsp; if (code_shown){&nbsp; &nbsp; &nbsp; $('div.input').hide('500');&nbsp; &nbsp; &nbsp; $('#toggleButton').val('Display code')&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; $('div.input').show('500');&nbsp; &nbsp; &nbsp; $('#toggleButton').val('Hide Code')&nbsp; &nbsp; }&nbsp; &nbsp; code_shown = !code_shown&nbsp; }&nbsp; $( document ).ready(function(){&nbsp; &nbsp; code_shown=false;&nbsp; &nbsp; $('div.input').hide()&nbsp; });</script><form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Display code"></form>''')单元格/片段 2:HTML('''<script></script><form action="javascript:IPython.notebook.execute_cells_below()"><input type="submit" id="toggleButton" value="Refresh"></form>''')单元格/片段 3:try: xexcept NameError: x = Noneif x is None:&nbsp; &nbsp; x = 0&nbsp; &nbsp; print(x)else:&nbsp; &nbsp; x = x + 1&nbsp; &nbsp; print(x)但是,我仍然无法漂亮地并排显示两个按钮,并且当我点击 时显示闪烁Refresh。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python