This can be done using an IPython ToggleButton
widget and a little bit of JavaScript. The following code should be placed into a code cell at the top of the document:
import ipywidgets as widgets
from IPython.display import display, HTML
javascript_functions = {False: "hide()", True: "show()"}
button_descriptions = {False: "Show code", True: "Hide code"}
def toggle_code(state):
"""
Toggles the JavaScript show()/hide() function on the div.input element.
"""
output_string = "<script>$(\"div.input\").{}</script>"
output_args = (javascript_functions[state],)
output = output_string.format(*output_args)
display(HTML(output))
def button_action(value):
"""
Calls the toggle_code function and updates the button description.
"""
state = value.new
toggle_code(state)
value.owner.description = button_descriptions[state]
state = False
toggle_code(state)
button = widgets.ToggleButton(state, description = button_descriptions[state])
button.observe(button_action, "value")
display(button)
This creates the following button to toggle showing/hiding the code for the Jupyter Notebook, defaulted to the "hide" state:
When set to the "show" state, you can then see the code for the Jupyter Notebook:
As an aside, while much of this code should be placed at the beginning of the Notebook, the location of the toggle button is optional. Personally, I prefer to keep it at the bottom of the document. To do so, simply move the display(button)
line to a separate code cell at the bottom of the page: