How to disable button when it is clicked?

Using :
Streamlit, version 1.36.0

pip 24.1.1

Python 3.11.7

Hello team , I have a streamlit app , when the user enters a prompt , I render 2 buttons for him to click , button used is st.button .
Now , when the button is clicked , I am making multiple api calls and this process takes time ( ~10 seconds ) .

I want to disable the button as soon as the user clicks on it .

How can I do so ?

you can use the property of st.button() called “disabled”, I suggest you to assign to the disabled property a st.session_state.* boolean variable to make a sort of on/off

I hope to answer to your question :slight_smile:

Hi @Jeremy_Sapienza , I’m using a session state variable for disabling the button and the state is getting updated but the button is not getting disabled at the moment I click the button . I want the button to become disabled as soon as I click it . But my button is behaving differently .

I’ve attached code snippet below .

def handle_button_click():
    print("button's state before clicking :",st.session_state.button_clicked.get(f"offer_{idx}",False))
    st.session_state.button_clicked[f"offer_{idx}"] = True
    print("button's state after clicking :",st.session_state.button_clicked[f"offer_{idx}"])
    url = multipleAPICallingFunction("call Function")
    print("url here :",url)
def buttonWasClicked(idx):
    # Check if the button was clicked
    val = st.session_state.button_clicked.get(f"offer_{idx}", False)
    print("is button clicked",val)
    return val

# Create a button and disable it if it was clicked
st.button(
    f"Click me (offer {idx})",
    on_click=handle_button_click,
    disabled=buttonWasClicked(idx)
)

Inside handle_button_click function , there is another function multipleAPICallingFunction which is getting called . this multipleAPICallingFunction further calls 4 apis ( REST apis and blockchain rpc api calls as well ) .

try something like this:

import streamlit as st
import time

import streamlit as st
import time

# if 'run_button' in st.session_state and st.session_state.run_button == True:
#     st.session_state.running = True
# else:
#     st.session_state.running = False

if st.button('Do a thing', disabled=st.session_state.get("run_button", False), key='run_button'):
    status = st.progress(0)
    for t in range(10):
        time.sleep(.2)
        status.progress(10*t+10)
    st.session_state.output = 'Selenium Output'
    st.rerun()

if 'output' in st.session_state:
    st.write(st.session_state.output)

updated from here : Disable the button until the end of the script execution - #7 by amiran

Here’s the solution

Result:

2024-10-28 9.36.05 p.m.