joergd joergd - 29 days ago 33
Python Question

Access data from bokeh widgets in a jupyter notebook

I want to use a text input widget in a jupyter notebook with autocompletion. I therefore used

AutocompleteInput()
from
bokeh.models.widgets.inputs
.

from bokeh.models.widgets.inputs import AutocompleteInput
from bokeh.io import output_notebook
from bokeh.plotting import show

output_notebook()

txt_input = AutocompleteInput(completions=['val1', 'val2'])
show(txt_input)


Displaying the widget and autocompletion works fine, but how can I access the value of the input widget upon change?
txt_input.value
only returns the default value (an empty string).

Answer

As of Bokeh 0.12.3, fuller integration of Bokeh widgets in the Jupyter notebook is still an open issue.

However, there are some workarounds, though they may be considered somewhat clunky. Here is a CustomJS callback you can pass to the widget that will set the value of a python value:

from bokeh.models import CustomJS

callback = CustomJS(code="""
if (IPython.notebook.kernel !== undefined) {
    var kernel = IPython.notebook.kernel;
    cmd = "widget_value = '" + cb_obj.value + "'";
    kernel.execute(cmd, {}, {});
}
""")

The result looks like:

enter image description here


The value of the cmd variable in the CustomJS code is string of python code that will be executed in your currently running Jupyter kernel. If you need to call some python function, e.g., you could do that too.