【发布时间】:2019-03-26 17:22:16
【问题描述】:
我想将一个滑块值(我使用 Bokeh 构建的)传回我的 Python 代码。该代码在绘图上生成 2 条线,并允许我更改其中一条的斜率和截距。但是当我引入回调 javascript 以将滑块值作为 "ff" 传递回我的 Python 代码时,它失败了。
你能帮我把滑块值返回给 python 的回调语法吗(例如,参见代码的最后一行 print(ff)) - 我确实想做一些比最终打印出来更有趣的事情!
来自回调的错误消息是:
ValueError: 期望一个 Dict(String, Instance(Model)) 的元素,得到 {'my_dict': {'s': 0.5}}
我的代码是:-
from ipywidgets import interact
import numpy as np
from bokeh.io import push_notebook, show, output_notebook
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
from bokeh.models.callbacks import CustomJS
output_notebook()
x = np.linspace(0, 20, 200) # create equally spaced points.
s = 0.5 # slope.
i = 3 # intercept.
y = s * x + i # straight line.
my_dict = dict(s=s) # need to create a dict object to hold what gets passed in the callback.
callback = CustomJS(args=dict(my_dict=my_dict), code="""
var ff = cb_obj.value
my_dict.change.emit()
""")
// ff should be the slider value.
p = figure(title="simple line example", plot_height=300, plot_width=600, y_range=(-20,20),
background_fill_color='#efefef')
r = p.line(x, y, color="#8888cc", line_width=1.5, alpha=0.8) # 1st line. This line can be controlled by sliders.
q = p.line(x, 2*x+1.2, color="#0088cc", line_width=1.9, alpha=0.2) # 2nd line.
def update(w=s, a=i):
r.data_source.data['y'] = w * x + a # allow updates for the line r.
push_notebook()
show(p, notebook_handle=True)
interact(update, w=(-10,10), a=(-12,12) )
print(ff) # Return what the slider value is. I want ff accessible back in my python code.
【问题讨论】: