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

如何在Python-Shiny中通过代码选中DataGrid表格的指定行?

Python版Shiny修改DataGrid选中行的方法

完全可以通过代码修改DataGrid的选中行,核心是使用update_data_frame函数实现程序化控制。

实现步骤及代码示例

  • 先从shiny.ui导入update_data_frame函数
  • 在server逻辑中,通过触发事件(比如按钮点击、响应式变量变化等)调用该函数,指定目标DataGrid的output_id和要选中的行

以下是完整示例代码:

from shiny import App, render, ui, reactive
import pandas as pd

app_ui = ui.page_fluid(
    ui.output_data_frame("grid"),
    ui.input_action_button("select_single_btn", "选中第2行"),
    ui.input_action_button("select_multi_btn", "选中第1、3行"),
    ui.input_action_button("clear_select_btn", "取消所有选中")
)

def server(input, output, session):
    @render.data_frame
    def grid():
        df = pd.DataFrame({
            "姓名": ["张三", "李四", "王五", "赵六"],
            "年龄": [25, 30, 28, 35]
        })
        return render.DataGrid(df, selection_mode="row")
    
    @reactive.Effect
    @reactive.event(input.select_single_btn)
    def _select_single_row():
        # 选中第2行(索引从0开始计数)
        ui.update_data_frame("grid", selected=1)
    
    @reactive.Effect
    @reactive.event(input.select_multi_btn)
    def _select_multiple_rows():
        # 选中第1、3行
        ui.update_data_frame("grid", selected=[0, 2])
    
    @reactive.Effect
    @reactive.event(input.clear_select_btn)
    def _clear_selection():
        # 取消所有选中行
        ui.update_data_frame("grid", selected=[])

app = App(app_ui, server)

关键说明

  • selected参数支持传入单个整数(单选)或整数列表(多选),对应行的索引(从0开始)
  • 除了按钮触发,也可以结合下拉框、文本输入等其他响应式组件,实现动态更新选中行的逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 07:04:51