如何更改 jupyter notebook/jupyterlab 中单个单元格的背景颜色? [英] How to change the background color of a single cell in a jupyter notebook / jupyterlab?
问题描述
我设计了一个笔记本,以便用户可以更改的变量被分组到整个笔记本中的不同单元格中.我想用不同的背景颜色突出显示这些单元格,以便用户清楚旋钮所在的位置.
我怎么能做到这一点?
注意:
使用 JupyterLab 0.32.1 在 Firefox 60 和 Chrome 67 中测试.
编辑以使其成为细胞魔法,您可以简单地执行以下操作:
from IPython.core.magic import register_cell_magic@register_cell_magic定义背景(颜色,单元格):设置背景(颜色)返回评估(单元格)
并像这样使用它:
%%背景蜜露my_important_param = 42
I design a notebook so that variables that could be changed by the user are grouped into distinct cells throughout the notebook. I would like to highlight those cells with a different background color so that it is obvious to the user where the knobs are.
How could I achieve that?
NB: This related question was about static code highlighting (for a manual) and the accepted answer proposed to basically put everything in markup comments. In my case, I want highlighted code to be in a runnable cell.
Here you go (assuming that you use Python kernel):
from IPython.display import HTML, display
def set_background(color):
script = (
"var cell = this.closest('.jp-CodeCell');"
"var editor = cell.querySelector('.jp-Editor');"
"editor.style.background='{}';"
"this.parentNode.removeChild(this)"
).format(color)
display(HTML('<img src onerror="{}" style="display:none">'.format(script)))
Then use it like this:
set_background('honeydew')
The solution is a bit hacky, and I would be happy to see a more elegant one. Demo:
Tested in Firefox 60 and Chrome 67 using JupyterLab 0.32.1.
Edit to have it as cell magic, you could simply do:
from IPython.core.magic import register_cell_magic
@register_cell_magic
def background(color, cell):
set_background(color)
return eval(cell)
and use it like:
%%background honeydew
my_important_param = 42
这篇关于如何更改 jupyter notebook/jupyterlab 中单个单元格的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!