I need an interactive data table where I can navigate through the rows using only the keyboard (e.g., arrow keys), and select a row without using the mouse. Once a row is selected, I should be able to extract that row’s data for further processing. The table should display data from a Pandas DataFrame and allow for smooth keyboard navigation and selection. Integration with Streamlit is preferred, but I’m open to other Python-based frameworks that support keyboard navigation and row selection
import streamlit as st
import pandas as pd
from st_aggrid import AgGrid, GridOptionsBuilder, DataReturnMode, GridUpdateMode, JsCode
Sample data similar to the rowData in the React code
row_data = [
{“name”: “Customer A”, “quote”: 100},
{“name”: “Customer B”, “quote”: 200},
{“name”: “Customer C”, “quote”: 150},
]
Convert to a DataFrame
df = pd.DataFrame(row_data)
Set up the grid options
gb = GridOptionsBuilder.from_dataframe(df)
gb.configure_selection(‘single’) # Enable single row selection
gb.configure_grid_options(enableRangeSelection=True, rowSelection=‘single’)
gb.configure_grid_options(domLayout=‘autoHeight’) # Auto height for better display
gb.configure_default_column(editable=True) # Enable cell editing
Add JavaScript code for navigating and selecting the next row
js_code = JsCode(“”"
function(event) {
console.log(event)
“”")
gb.configure_grid_options(onCellKeyDown=js_code)
grid_options = gb.build()
Display the Ag-Grid table in Streamlit with editable and navigable rows
grid_response = AgGrid(
df,
gridOptions=grid_options,
data_return_mode=DataReturnMode.FILTERED_AND_SORTED,
update_mode=GridUpdateMode.SELECTION_CHANGED | GridUpdateMode.MODEL_CHANGED, # Capture changes and selections
fit_columns_on_grid_load=True,
height=400,
theme=‘alpine’,
enable_enterprise_modules=False,
)
Capture the modified data after edits
updated_df = grid_response[‘data’]
Get the selected row
selected_row = grid_response[‘selected_rows’]
Display the selected row
st.subheader(“Selected Row:”)
st.dataframe(selected_row)
Display the updated dataframe
st.subheader(“Updated DataFrame:”)
st.dataframe(updated_df)
Instructions for keyboard navigation
st.write(“Use arrow keys (↑/↓) to navigate and select rows. Double-click to edit a cell, and press Enter to save the change.”)
see this code