我想在 Jupyter Notebook 的开头添加某种功能,以隐藏/显示所有单元格并重新运行所有单元格。我最终想要的是一组图表,当重新运行所有单元格时,这些图表会被刷新。
详细信息和我尝试过的内容:
帖子IPython - Run all cells below from a widget显示了如何添加按钮以重新运行下面的所有单元格。和帖子How to hide code from cells in ipython notebook visualized with nbviewer? .通过在两个不同的单元格中进行此设置,我最终得到了这个:
当单元格折叠时,它看起来像这样:
这很好用,但我真的很好奇是否可以格式化按钮以使它们看起来相同。也许可以将它们对齐为同一单元格的输出?我试图通过将两个片段放在同一个单元格中来做到这一点,但现在看来 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:
有谁知道如何让它更优雅一点?
最佳答案
我真的希望有人能够提供更好的答案,但经过几个小时的尝试和失败后,我发现了这个:
通过简单地混合问题中两个片段的一些部分,我能够以与 Hide Code buttion
相同的格式设置一个 Refresh button
:
输出/笔记本 View :
但这仍然需要两个不同单元格中的两个代码片段,以及第三个单元格中的一些测试代码:
单元格/片段 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
时,显示会闪烁。
关于python - 如何隐藏代码并重新运行 jupyter notebook 中的所有单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54592814/