Updating help text for widget based on user selection?

Hi there!

I was wondering if it was possible to set the help text attribute in a widget like st.selectbox based on what is selected. For example, if I create an st.selectbox where the user selects a variable to plot on the x axis of a plot, I’d like to have the help text show a description of the variable they have chosen. Of course, I cannot get the description without first knowing what variable the user has selected.

Is it possible to not display the selectbox until I can get the user input and update it with the appropriate help text? Or to create some help text that’s next to/inline the selectbox label instead of above or below it?

Thanks!

Here’s a basic example:

import streamlit as st

if "my_key" not in st.session_state:
    st.session_state.my_key = "Default"

st.session_state.my_key=st.session_state.my_key
st.selectbox(
    "Make a selection",
    ["Default", "Apple", "Banana", "Carrot"],
    key="my_key",
    help=f"You've selected {st.session_state.my_key}"
)

Important notes:

  1. Assign a key to the widget and initialize that key at the beginning of your app before the widget loads. (This sets the default value and makes sure the value is immediately available to set your help text.)
  2. Copy the key value to itself before the widget. This avoids creating a “double submission” problem. The help text is part of the widget’s identity, so if you change it, Streamlit will destroy your previous widget and create a new one. By copying the key, you unpair the value in Session State from the instance of the widget from the previous run and make it availalble to initialize a “new” widget. (In practice, it just makes its work as expected when changing the widget’s identity.)
1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.