How do I properly enable/disable a button? I’m attempting to enable button_c when button_a clicked; disable button_c when button_b clicked. Default is disabled. As far as I understand, this is in session_state. Below code is my attempt, not working.
import streamlit as st
if 'but_a' not in st.session_state:
st.session_state.disabled = True
button_a = st.button('a', key='but_a')
button_b = st.button('b', key='but_b')
button_c = st.button('c', key='but_c', disabled=st.session_state.disabled)
st.write(button_a, button_b, button_c)
if button_a:
st.write("clicked A")
st.session_state.disabled = False
if button_b:
st.write('clicked B')
st.session_state.disabled = True
What is happening, IIUC, is that as soon as you click the button (and, crucialy, before st.session_state.disabled is updated), the app is rerun. Then the buttons are drawn again (using the old value in st.session_state.disabled) and only after that is st.session_state.disabled assigned the new value, but a this point the buttons have been already drawn. As a result, you need to click twice to redraw everything and see the changes.
The solution is assigning to st.session_state.disabledbefore calling st.button, but you have to make it work even when the buttons do not exist yet (first run).
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.