Hi all,
I want to make two buttons that when a user clicks one button (A) then a question (a) is displayed; when the user clicks the other button (B) then another question (b) is displayed and the previous question (a) disappears.
Code is below
if "AAA" not in st.session_state:
st.session_state.AAA = False
if "BBB" not in st.session_state:
st.session_state.BBB = False
A = st.button("A")
B = st.button("B")
if A or st.session_state.AAA:
st.session_state.AAA = True
st.session_state.BBB = False
st.radio('a',('a','a','a'))
if B or st.session_state.BBB:
st.session_state.BBB = True
st.session_state.AAA = False
st.radio('b', ('b','b'))
My code works when I switch from session state AAA to BBB, but not the reverse way.
For more details, when question a is displayed, I clicked button B and question b appears but question a is still there.
Thank you!
1 Like
Hi Anhhaokudo,
Welcome to Streamlit
My solution is a bit of a lazy one but it works for me:
import streamlit as st
if "current" not in st.session_state:
st.session_state.current = None
if "AAA" not in st.session_state:
st.session_state.AAA = False
if "BBB" not in st.session_state:
st.session_state.BBB = False
A = st.button("A")
B = st.button("B")
if A:
st.session_state.current = "A"
if B:
st.session_state.current = "B"
if st.session_state.current != None:
if st.session_state.current == "A":
st.session_state.AAA = True
st.session_state.BBB = False
st.radio('a',('a','a','a'))
else:
st.session_state.BBB = True
st.session_state.AAA = False
st.radio('b', ('b','b'))
I use this in my own apps as well but with the dispatch pattern to look up what the current clicked button is and call the according function/Streamlit page widgets that I need.
Not sure if there’s a better way but this works for me
Have an awesome day!
2 Likes
You are a wizard!
It works for me!!
Thank you so much and have a great weekend.
1 Like
haha no problem at all, Streamlit sometimes requires a little bit of magic
Just to expand on your idea a bit more, if you want to have a load of buttons and show something different for each button you can do what I did for my app.
- Define a function for each “page with widgets” that you want
- Add a reference to the function in a dictionary
import streamlit as st
def button_one():
st.radio('a',('a','a','a'))
def button_two():
st.radio('b',('b','b'))
pages = {
0 : button_one,
1 : button_two,
}
if "current" not in st.session_state:
st.session_state.current = None
# Now you can set the button click to a number and call the linked function
if st.button("A"):
st.session_state.current = 0
if st.button("B"):
st.session_state.current = 1
if st.session_state.current != None:
pages[st.session_state.current]()
There’s probably an even better way to handle this but this is what I’m using
Have a great weekend as well!
2 Likes