3

I'm trying to write a simple user interface for Python code in a Jupyter/IPython notebook. I'm using the amazing ipywidgets. I need to find a way to prevent users from clearing the widgets by accidentally clicking the <button class="close">×</button> (the X to the left of the widgets). I've spent hours searching for a simple way to do this. Here's a simple, minimal example of the issue in a single Jupyter notebook cell:

import ipywidgets
import IPython.display

w = ipywidgets.IntSlider()

IPython.display.display(w)

The result is a slider with the widget clear button X to the left of the slider:

Image of slider with widget clear button X

How can I remove or disable the widget clear button so that the user can't accidentally clear the widget?

jcmaxwell
  • 31
  • 1
  • 4

1 Answers1

1

I was looking into the same problem and solved it by some hack. So dropping off my solution here:

In your running notebook, run this code in a cell:

from IPython.display import HTML

htmlscript_ipywidget_disable_closing = '''<script>
disable = true
function disable_ipyw_close(){
    if(disable){
        $('div.widget-area > div.prompt > button.close').hide()
    }
    else{
        $('div.widget-area > div.prompt > button.close').show()    
    }
    disable = !disable
}
$( document ).ready(disable_ipyw_close);
</script>

<form action="javascript:disable_ipyw_close()"><input style="opacity: 0.5" type="submit" value="Disable ipywidget closing"></form>'''
# change opacity to 0 to hide this button itself
HTML(htmlscript_ipywidget_disable_closing)

A Button will appear in the output which will toggle the visibility of those ipywidget close buttons. This was heavily inspired by the top answer here, which was about hiding all input cells.

Foon
  • 221
  • 1
  • 7