joergd joergd - 9 months ago 122
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


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


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

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

Answer Source

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.