How do I change the label of the button when it is clicked?

I have to been trying for days

import streamlit as sl
opt = sl.button(label = "hello")
if opt:
    # need to change the label of the "opt" button```

You can’t do it directly, but you can create the effect. I’m not sure exactly what process you’re running and how you want it to change (and maybe change back or be temporarily disabled), but here is one example:

import streamlit as st

if "A_label" not in st.session_state:
    st.session_state.A_label = "A"
    st.session_state.A_triggered = False
    st.session_state.B_label = "B"
    st.session_state.B_triggered = False

def run_A():
    st.session_state.A_label = "Running A"
    st.session_state.A_triggered = True

def run_B():
    st.session_state.B_label = "Running B"
    st.session_state.B_triggered = True

st.button(st.session_state.A_label, on_click=run_A)
if st.session_state.A_triggered:
    st.session_state.A_triggered = False
    st.session_state.A_label = "A"
    # do something

st.button(st.session_state.B_label, on_click=run_B)
if st.session_state.B_triggered:
    st.session_state.B_triggered = False
    st.session_state.B_label = "B"
    # do something

You can’t change the label on a button after it’s rendered; you can only change the label on the next rerun. Furthermore, if you change the label on the button it becomes a “different button” to Streamlit so there are extra details to use it.

In the example, I’ve pulled out the label and value of the button into Session State to handle manually and don’t use the output of the button at all.

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