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

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

详细信息和我尝试过的方法

帖子IPython – Run all cells below from a widget显示了如何添加按钮以重新运行下面的所有单元格.以及帖子How to hide code from cells in ipython notebook visualized with nbviewer?.在两个不同的单元格中进行了此设置,最终得到了以下结果:

enter image description here

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

enter image description here

效果很好,但是我真的很好奇是否可以格式化按钮,使它们看起来一样.也许可以将它们作为同一单元的输出进行对齐?我试图通过在同一单元格中包含两个代码片段来做到这一点,但是现在看来,“隐藏”按钮被“刷新”按钮覆盖了:

片段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:

enter image description here

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

最佳答案
我真的希望有人能够提供更好的答案,但是经过数小时的尝试和失败,我发现了这一点:

通过简单地混合问题中两个片段的一部分,我就可以设置一个与“隐藏代码”按钮格式相同的“刷新”按钮:

输出/笔记本视图:

enter image description here

但这仍然需要两个不同单元中的两个代码段,以及第三个单元中的一些测试代码

单元格/摘录1:

from IPython.display import HTML

HTML('''<script>
  function code_toggle() {
    if (code_shown){
      $('div.input').hide('500');
      $('#toggleButton').val('Display 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="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: x
except NameError: x = None

if x is None:
    x = 0
    print(x)
else:
    x = x + 1
    print(x)

但是,我仍然不能漂亮地并排显示两个按钮,并且当我按下Refresh时,屏幕会闪烁.

相关文章

在这篇文章中,我们深入学习了XPath作为一种常见的网络爬虫技巧。XPath是一种用于定位和选择XML文档中特...
祝福大家龙年快乐!愿你们的生活像龙一样充满力量和勇气,愿你们在新的一年里,追逐梦想,勇往直前,不...
今天在爬虫实战中,除了正常爬取网页数据外,我们还添加了一个下载功能,主要任务是爬取小说并将其下载...
完美收官,本文是爬虫实战的最后一章了,所以尽管本文着重呈现爬虫实战,但其中有一大部分内容专注于数...
JSON是一种流行的数据传输格式,Python中有多种处理JSON的方式。官方的json库是最常用的,它提供了简单...
独立样本T检验适用于比较两组独立样本的均值差异,而配对T检验则适用于比较同一组样本在不同条件下的均...