You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用TextInput组件过滤Bokeh DataTable中的字符串列?

Bokeh DataTable 实现TextInput过滤内容的修复方案

你的代码逻辑方向是对的,但因为缺少过滤条件变更的触发事件,导致表格不会根据输入内容刷新。以下是修复后的完整代码:

import random
import string
import pandas as pd

from bokeh.io import show
from bokeh.models import TextInput, ColumnDataSource, CustomJS, Column, BooleanFilter, CDSView, TableColumn, DataTable


def random_str():
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(20))


data = dict(options=[random_str() for _ in range(500)])
df = pd.DataFrame(data=data)
source = ColumnDataSource(data=data)

text_filter = BooleanFilter(booleans=[True] * df.shape[0])
view = CDSView(filter=text_filter)

columns = []
for col in list(df.columns):
    columns.append(TableColumn(field=col, title=col))
data_table = DataTable(source=source, columns=columns, height=500, width=300, view=view)

# Setting initial values
text_input = TextInput(value="", title="Enter filter")
callback = CustomJS(args=dict(source=source, text_filter=text_filter),
                    code="""
    // 直接遍历数据源数组,生成过滤后的布尔数组
    text_filter.booleans = source.data['options'].map(t => 
        // 可选:转为小写实现大小写不敏感过滤
        t.toLowerCase().includes(cb_obj.value.toLowerCase())
    );
    // 触发过滤条件变更事件,通知视图刷新
    text_filter.change.emit();
""")
text_input.js_on_change("value", callback)

show(Column(text_input, data_table))

关键修改说明:

  • 添加text_filter.change.emit();:Bokeh不会自动监听BooleanFilter.booleans的属性变化,必须手动触发变更事件,才能让关联的CDSView重新计算并刷新表格的显示内容。
  • 优化数组遍历:移除不必要的Array.from(),因为source.data['options']本身就是JS数组类型,直接调用map即可。
  • 可选的大小写不敏感过滤:将文本转为统一小写后再判断包含关系,避免因大小写差异导致的过滤遗漏,提升用户体验。

内容的提问来源于stack exchange,提问作者DaniK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 09:35:13