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

前端 未结 3 1938
鱼传尺愫
鱼传尺愫 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:34

    Small addition to krassowski's code (tried to add it as comment but couldn't get the formatting to work).

    from IPython.core.magic import register_cell_magic
    from IPython.display import HTML, display
    
    @register_cell_magic
    def bgc(color, cell=None):
        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)))
    

    This way you can use it both as magic and with normal function call:

    bgc('yellow')
    bla = 'bla'*3
    

    or

    %%bgc yellow
    bla = 'bla'*3
    

提交回复
热议问题