How to use st.dataframe, on_select, callable

I am trying to set up a dataframe with selectable rows using st.dataframe’s on_select and the callable option.

        selection = st.dataframe(
            projects_df,
            use_container_width=True,
            hide_index=True,
            selection_mode="single-row",
            on_select=handle_selection_change
        )

According to the document:

A callable: Streamlit will rerun the app and execute the callable as a callback function before the rest of the app. In this case, st.dataframe will return the selection data as a dictionary.

When it calls my function, how does the return value of st.dataframe get to my function?

You can access it using the app’s session state.

dataframe_callback

Code
import streamlit as st
import pandas as pd

def callback():
    with st.sidebar:
        st.write("**Callback called**")
        st.write(st.session_state.df)


def main():
    df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})

    st.title("Callback example")

    st.dataframe(
        df,
        on_select=callback,
        selection_mode="multi-row",
        key="df",
    )


if __name__ == "__main__":
    main()

How do we pass the selected row index value to the function? Can we do that?

You don’t. You have the selections in st.session_state.df.

Yeah finally used that as per above example, thanks!

I want to use the callback to display things, when I use st.write I can’t find the display anywhere. I’ve been able to successfully display things in the sidebar as per the example but that is not ideal for displaying pdfs. Any advice?

@maustin What are you trying to do specifically? The selection event information in Session State or from the dataframe command is just information in Python. You can take the information to filter out the selected row and show that information (whether that’s in the sidebar or not), or you can use that information to query some other data and show that. There’s nothing special about how you use the selected row or where you show something as a result of it.

For example, if you have a dataframe with file names and someone selects a row, you can use the returned row index to lookup up the name of the file in your original dataframe, then use the filename string to go read the file and display something from it.

ah, I see. I’m trying to display the pdf that the selected row is associated with. Right now I do that by using a callback on selection. If I’m understanding correctly though, you’re saying I could set on_click to ignore or rerun and just use the session state for the selected information. That worked perfectly! thanks :slight_smile: