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?