Reputation: 85
I am using Jupyter notebook with Python 3 kernel. I have a computation which bases on user input by an IPython widget. The result of the computation needs to be shown in a markdown cell. For this I use the Python Markdown nbextension. The Question now is: How do I update the markdown cell on user interaction?
I tried to run the markdown cell from python using a Javascript call. As a minimal example, the following two cells may serve. (First normal python cell, second markdown cell)
from IPython.display import Javascript
import ipywidgets
def update_md_cell(slider_value):
Javascript("Jupyter.notebook.execute_cells([1])")
t_slider = ipywidgets.IntSlider(min = 0, max = 10, value = 10)
ipywidgets.interactive(update_md_cell, slider_value = t_slider)
... The value of number is {{t_slider.value}}. ...
But this seems to work only outside of functions.
Javascript("Jupyter.notebook.execute_cells ([1])")
reloads the markdown cell.
def update_md_cell():
Javascript("Jupyter.notebook.execute_cells ([1])")
update_md_cell()
does nothing.
Is there another way to connect the inputs (through the IPython widget) to the output (in the Markdown cell)?
Update: Like mentioned in the comment to Suraj Potnuru's answer, my basic problem is the gotcha from here:
A big gotcha: something somewhere needs to return Javascript as its output, otherwise it doesn’t get executed in the notebook.
But it's even worse, a return in the via ipywidgets.interactive() binded function is not enough to fix the gotcha, e.g.:
def update_md_cell():
return Javascript("Jupyter.notebook.execute_cells ([1])")
update_md_cell()
works.
from IPython.core.display import Javascript
from IPython.display import display
import ipywidgets
def update_md_cell(slider_value):
return Javascript("Jupyter.notebook.execute_cells ([1])")
t_slider = ipywidgets.IntSlider(min = 0, max = 10, value = 10)
ipywidgets.interactive(update_md_cell, slider_value = t_slider)
doesn't work.
How do I get the second to work?
Upvotes: 1
Views: 1950
Reputation: 101
Update your foo() function to the below code
def foo():
slider_value = t_slider.value
display(Javascript("var markdown_cell = IPython.notebook.get_cell(1);markdown_cell.set_text('The value of the number is "+ str(slider_value) +"');IPython.notebook.execute_cell(1)"))
The above code snippet fetches the value of the slider object and uses get_cell()
function to fetch the first cell which is your markdown cell. The cells numbering starts from 0, hence 0th cell is your python code cell, 1st cell is your markdown cell.
It uses the set_text()
function to update the markdown inside your cell with the latest slider value.
Call foo()
function whenever your slider is updated to update the markdown also.
Upvotes: 1