How to change the background color of a single cell in a jupyter notebook / jupyterlab?

前端 未结 3 1934
鱼传尺愫
鱼传尺愫 2021-01-02 04:41

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

3条回答
  •  情歌与酒
    2021-01-02 05:27

    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(''.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
    

提交回复
热议问题