如何更改Jupyter Notebook/Jupyterlab中单个单元格的背景颜色? [英] How to change the background color of a single cell in a jupyter notebook / jupyterlab?
问题描述
我设计了一个笔记本,以便用户可以更改的变量在整个笔记本中分为不同的单元格.我想用不同的背景色突出显示这些单元格,以便用户在哪里看到旋钮.
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.
我该如何实现?
NB:这个相关问题是关于 static 代码突出显示(用于手册),并提出了可接受的答案,以便将所有内容基本上都放入标记注释中.就我而言,我希望突出显示的代码位于可运行单元格中.
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.
推荐答案
在这里(假设您使用的是Python内核):
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)))
然后像这样使用它:
set_background('honeydew')
该解决方案有点笨拙,我很高兴看到一个更优雅的解决方案. 演示:
The solution is a bit hacky, and I would be happy to see a more elegant one. Demo:
使用JupyterLab 0.32.1在Firefox 60和Chrome 67中进行了测试.
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)
并像这样使用它:
%%background honeydew
my_important_param = 42
这篇关于如何更改Jupyter Notebook/Jupyterlab中单个单元格的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!