Hi!,
This problem has occured to many before, and it is one of the most common on this forum:
Your answer should be in the above link. However, I have given an explanation here as well.
Your problem can be solved by using st.session_state
. Whenever the state of a widget changes in Streamlit, it reruns the script. That is why your button goes back to a normal ‘unclicked’ state and your text is not visible.
However, in Streamlit, you can store values in the session state, which persists across reruns. So your code for the click function will be:
import streamlit as st
'''
We store a parameter named 'button_clicked'(Name can be changed) in session state.
At the start of our session, we set it to False. Once the button is clicked, we can
change it to True. This will not reset when page is reloaded upon selecting option.
'''
if 'button_clicked' not in st.session_state:
st.session_state['button_clicked'] = False
def fonction_click1():
mybutton=st.button('first click')
if not st.session_state['button_clicked']: # if button has not been clicked
if mybutton:
st.write('clicked_1')
st.session_state['button_clicked'] = True #our button has been clicked now
else:
st.write('clicked_1')
fonction_click1()
option = st.selectbox(
'How would you like to be contacted?',
('Email', 'Home phone', 'Mobile phone'))
st.write('You selected:', option)
Now, the text will persist since we are checking the session state variable to decide writing the text. This can probably be executed in a much simpler way, but this is what I came up with.
Here are some links to understand session state better:
Please check if a solution for your problem has already been given by someone previously, before posting a question here
Cheers!
Moiz