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

关于NiceGUI中ui table()绑定bind filter()实现搜索功能的咨询

在NiceGUI中实现表格搜索过滤功能

基础实现示例

直接通过ui.input绑定表格的filter属性,就能快速实现全局搜索:

from nicegui import ui

# 模拟数据源
table_rows = [
    {'name': 'Alice', 'age': 25, 'city': 'New York'},
    {'name': 'Bob', 'age': 30, 'city': 'London'},
    {'name': 'Charlie', 'age': 35, 'city': 'Paris'},
]

# 创建搜索输入框,绑定到表格的过滤逻辑
search_input = ui.input(label='搜索').props('rounded outlined')

# 定义表格列
table_columns = [
    {'name': 'name', 'label': '姓名', 'field': 'name'},
    {'name': 'age', 'label': '年龄', 'field': 'age'},
    {'name': 'city', 'label': '城市', 'field': 'city'},
]

# 创建表格并绑定过滤
ui.table(columns=table_columns, rows=table_rows).bind_filter(search_input)

ui.run()

bind_filter() 可调用内容详解

bind_filter() 支持两种绑定方式,核心围绕响应式变量和过滤函数展开:

1. 直接绑定响应式变量

你可以直接把ui.input的响应式实例(或ui.reactive创建的变量)传给bind_filter():

  • 此时NiceGUI会自动使用默认过滤逻辑:遍历行数据的所有字段,检查是否包含关键词(大小写不敏感,支持数字、字符串的模糊匹配)
  • 空关键词时会显示所有数据

2. 自定义过滤函数

如果默认逻辑不满足需求,你可以传入自定义过滤函数,函数需满足:

  • 接收两个参数:第一个是单条行数据(dict或自定义对象),第二个是搜索关键词
  • 返回布尔值:True保留该行,False过滤该行

示例(仅在姓名和城市字段搜索,区分大小写):

from nicegui import ui

table_rows = [
    {'name': 'Alice', 'age': 25, 'city': 'New York'},
    {'name': 'Bob', 'age': 30, 'city': 'London'},
    {'name': 'Charlie', 'age': 35, 'city': 'Paris'},
]

def custom_filter(row: dict, query: str) -> bool:
    if not query:
        return True
    # 仅在name和city字段匹配,区分大小写
    return query in row['name'] or query in row['city']

search_input = ui.input(label='精准搜索')
table_columns = [
    {'name': 'name', 'label': '姓名', 'field': 'name'},
    {'name': 'age', 'label': '年龄', 'field': 'age'},
    {'name': 'city', 'label': '城市', 'field': 'city'},
]

# 绑定自定义过滤函数
ui.table(columns=table_columns, rows=table_rows).bind_filter(search_input, custom_filter)

ui.run()

绑定注意事项

  • 绑定的变量必须是响应式对象(比如ui.input实例,或ui.reactive(str())创建的变量)
  • 自定义函数的参数顺序不可颠倒:行数据在前,过滤值在后
  • 若过滤值为空,建议返回True,确保显示全部数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 19:30:09