我想建立一个DataTable,当用户按下某行时,它将运行一个回调。回调需要有第一列的值(对于选定的行)。
我试了一些方法,但都没有成功。
from bokeh.layouts import widgetbox, row, column
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.models.widgets import Button, RadioButtonGroup, RadioGroup, Tabs, \
TextInput, Panel, Div, Select, DataTable, TableColumn, DateFormatter, \
Slider
from bokeh.plotting import curdoc, show
import db_lib # database interaction
import dataAnalyzer
testBox = TextInput(title="test box", value = "start text")
# getting the data here:
data = {}
data["patients"] = {'kyma PT #': [1297, 1301, 1305, 1312], 'client PT #': [15072, 15255, 15228, 15077], 'patient name': ['John', 'David', 'Mark', 'Martin']}
patients_col = [
TableColumn(field="kyma PT #", title="Kyma PT #", width = 50),
TableColumn(field="client PT #", title="Client PT #", width = 50),
TableColumn(field="patient name", title="Patient Name", width = 200),
]
patients_src = ColumnDataSource(data["patients"])
# method 1
source_code = """
row = cb_obj.indices[0]
testBox.update(value=patients_src.data["kyma PT #"][row])
"""
callback = CustomJS(args = dict(source = patients_src), code = source_code)
patients_src.selected.js_on_change('indices', callback)
layout = column(testBox)
show(layout)
这个会显示一个错误: "'Instance'的实例没有'js_on_change'成员",它没有崩溃地运行,但在表中选择没有任何作用。
# method 2
def table_select(attr, old, new):
testBox.update(value=patients_src.data["kyma PT #"][row])
patients_src.selected.on_change('indices', table_select)
和第一次尝试的情况一样
# method 3
def table_select(attr, old, new):
testBox.update(value=patients_src.data["kyma PT #"][row])
patients_src.on_change('selected', table_select)
没有出错,但回调没有运行。
值得注意的是,我也在服务器上运行它(curdoc()),但结果是一样的。
你的代码还是不完整:有一些不存在的模块的导入,而且表也找不到了。
然而,这些似乎很容易解决。你的代码的主要问题是,你在编写的JavaScript代码是为 CustomJS
就像Python代码一样。
这是你代码的工作版本。
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, CustomJS, DataTable
from bokeh.models.widgets import TextInput, TableColumn
from bokeh.plotting import show
testBox = TextInput(title="test box", value="start text")
patients_col = [
TableColumn(field="kyma PT #", title="Kyma PT #", width=50),
TableColumn(field="client PT #", title="Client PT #", width=50),
TableColumn(field="patient name", title="Patient Name", width=200),
]
patients_src = ColumnDataSource({'kyma PT #': [1297, 1301, 1305, 1312],
'client PT #': [15072, 15255, 15228, 15077],
'patient name': ['John', 'David', 'Mark', 'Martin']})
source_code = """
const row = cb_obj.indices[0];
testBox.value = source.data["kyma PT #"][row].toString();
"""
callback = CustomJS(args=dict(source=patients_src, testBox=testBox), code=source_code)
patients_src.selected.js_on_change('indices', callback)
layout = column(testBox, DataTable(columns=patients_col, source=patients_src))
show(layout)