J Beckford
J Beckford

Reputation: 149

Streamlit Button Change Disabled State

How can I get a button to enable/disable properly in streamlit? Current code below works on 1 click delay (not desired).

Desired action -- Enable button_c when button_a clicked and disabled when button_b clicked.

Current action -- button_c enabled after button_a clicked and then any other button, or disabled after button_b clicked and any other button.

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
    

Upvotes: 2

Views: 8740

Answers (1)

furas
furas

Reputation: 142983

I think all problem is it runs all code again when you press any button, and it creates again all buttons, and you have to change state before it creates button_c.

if button_a:
    st.session_state.disabled = False

if button_b:
    st.session_state.disabled = True

button_c = st.button('c', key='but_c', disabled=st.session_state.disabled)

Full working code:

import streamlit as st

if 'but_a' not in st.session_state:
    st.session_state.disabled = True

print('before:', st.session_state)

button_a = st.button('a', key='but_a')

button_b = st.button('b', key='but_b')

# change state before creating button `c` (but after creating button `a` and `b`)

if button_a:
    st.session_state.disabled = False

if button_b:
    st.session_state.disabled = True

button_c = st.button('c', key='but_c', disabled=st.session_state.disabled)

st.write(button_a, button_b, button_c)

# display text after displaying all buttons

if button_a:
    st.write("clicked A - Activate C")

if button_b:
    st.write("clicked B - Deactivate C")

print('after:', st.session_state)

Upvotes: 2

Related Questions