#!/usr/bin/env python # coding: utf-8 # # Automatic creation of new code cells via widgets # # This code was originally written by Jonathan Frederic. For full context, see [GH issue 4983 in IPython](https://github.com/ipython/ipython/issues/4983), as well as [5006](https://github.com/ipython/ipython/issues/5006) and [#44 in ipywidgets](https://github.com/ipython/ipywidgets/issues/44). # # The code below demonstrates quickly how to make a widget that injects a new code cell into the notebook. # In[1]: import base64 from IPython.display import Javascript, display from IPython.utils.py3compat import str_to_bytes, bytes_to_str def create_code_cell(code='', where='below'): """Create a code cell in the IPython Notebook. Parameters code: unicode Code to fill the new code cell with. where: unicode Where to add the new code cell. Possible values include: at_bottom above below""" encoded_code = bytes_to_str(base64.b64encode(str_to_bytes(code))) display(Javascript(""" var code = IPython.notebook.insert_cell_{0}('code'); code.set_text(atob("{1}")); """.format(where, encoded_code))) # In[2]: from ipywidgets import Button def on_click(button): create_code_cell('print("Hello world!")') button = Button(description="Create code") button.on_click(on_click) button # In[ ]: print("Hello world!")