Skip to content

Instantly share code, notes, and snippets.

@fperez
Created January 29, 2016 04:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fperez/0fb77c5faea8996208a7 to your computer and use it in GitHub Desktop.
Save fperez/0fb77c5faea8996208a7 to your computer and use it in GitHub Desktop.
Automatic creation of new code cells via widgets.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Automatic creation of new code cells via widgets\n",
"\n",
"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).\n",
"\n",
"The code below demonstrates quickly how to make a widget that injects a new code cell into the notebook."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import base64\n",
"from IPython.display import Javascript, display\n",
"from IPython.utils.py3compat import str_to_bytes, bytes_to_str\n",
"\n",
"def create_code_cell(code='', where='below'):\n",
" \"\"\"Create a code cell in the IPython Notebook.\n",
"\n",
" Parameters\n",
" code: unicode\n",
" Code to fill the new code cell with.\n",
" where: unicode\n",
" Where to add the new code cell.\n",
" Possible values include:\n",
" at_bottom\n",
" above\n",
" below\"\"\"\n",
" encoded_code = bytes_to_str(base64.b64encode(str_to_bytes(code)))\n",
" display(Javascript(\"\"\"\n",
" var code = IPython.notebook.insert_cell_{0}('code');\n",
" code.set_text(atob(\"{1}\"));\n",
" \"\"\".format(where, encoded_code)))"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from ipywidgets import Button\n",
"def on_click(button):\n",
" create_code_cell('print(\"Hello world!\")')\n",
" \n",
"button = Button(description=\"Create code\")\n",
"button.on_click(on_click)\n",
"\n",
"button"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(\"Hello world!\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "IPython (Python 3)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.1"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment