pythondatatabledatagridreactive-programmingpy-shiny

How to select certain row(s) by code in a DataGrid table in Python-Shiny?


I created a table ("DataGrid") using:

ui.output_data_frame("grid")

which I filled using

@render.data_frame
def grid(): 
    df = ...  
    return render.DataGrid(df, selection_mode="row")

Now, I want to change the selection using codfe. Is this possible in Python's version of Shiny?


Solution

  • You can use update_cell_selection():

    from shiny import ui, render, App, reactive
    import pandas as pd
    
    df = pd.DataFrame({"Row": ["Row Number 0", "Row Number 1", "Row Number 2"]})
    
    app_ui = ui.page_fluid(
        ui.input_select(
            "rowSelection", 
            "Which row shall be selected?", 
            choices=["Choose", 0, 1, 2]
        ),
        ui.output_data_frame("my_df")
    )
    
    def server(input, output, session):  
        
        @render.data_frame
        def my_df():
            return render.DataGrid(df, selection_mode="row")
        
        @reactive.Effect 
        @reactive.event(input.rowSelection)
        async def setSelection():
            if (input.rowSelection() == "Choose"): return
            x={'type': 'row', 'rows': int(input.rowSelection())}
            await my_df.update_cell_selection(x)
    
    app = App(app_ui, server)
    

    enter image description here