从 jupyter 笔记本中的散景小部件访问数据
Access data from bokeh widgets in a jupyter notebook
我想在具有自动完成功能的 jupyter 笔记本中使用文本输入小部件。因此,我使用了 bokeh.models.widgets.inputs
.
中的 AutocompleteInput()
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,但是我如何在更改时访问输入小部件的值? txt_input.value
仅 returns 默认值(空字符串)。
从 Bokeh 0.12.3
开始,Jupyter notebook 中 Bokeh 小部件的更全面集成是 still an open issue。
但是,也有一些解决方法,尽管它们可能被认为有些笨拙。这是一个 CustomJS
回调,您可以将其传递给将设置 python 值的小部件:
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, {}, {});
}
""")
结果如下:
CustomJS
代码中 cmd
变量的值是 python 代码的字符串,将在您当前的 运行 Jupyter 内核中执行。例如,如果您需要调用某些 python 函数,您也可以这样做。
我想在具有自动完成功能的 jupyter 笔记本中使用文本输入小部件。因此,我使用了 bokeh.models.widgets.inputs
.
AutocompleteInput()
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,但是我如何在更改时访问输入小部件的值? txt_input.value
仅 returns 默认值(空字符串)。
从 Bokeh 0.12.3
开始,Jupyter notebook 中 Bokeh 小部件的更全面集成是 still an open issue。
但是,也有一些解决方法,尽管它们可能被认为有些笨拙。这是一个 CustomJS
回调,您可以将其传递给将设置 python 值的小部件:
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, {}, {});
}
""")
结果如下:
CustomJS
代码中 cmd
变量的值是 python 代码的字符串,将在您当前的 运行 Jupyter 内核中执行。例如,如果您需要调用某些 python 函数,您也可以这样做。