Iām making an app and I have a problem, I want one button to check if the answer is correct and then I want to Hide/Disable the button because otherwise, you can press the check answer button how many times you want to get super many points. I have made a similar example to this to show you.
import streamlit as st
if "score" not in st.session_state:
st.session_state["score"] = 0
user_answer = st.number_input("1 + 1")
if st.button("Check answer"):
if user_answer == 2:
st.session_state["score"] += 1
st.write("Correct! Score: " + str(st.session_state["score"]))
else:
st.write("Wrong! Score: " + str(st.session_state["score"]))
#Hide/disable button
Here is a sample scheme. Just see the comments in the code.
import streamlit as st
import time
# Create a session variable to disable number input and
# button widgets when answer is correct.
if 'q1_disabled' not in st.session_state:
st.session_state.q1_disabled = False
# Define score session variable to keep track of score.
if "score" not in st.session_state:
st.session_state["score"] = 0
# Reset the disabled states of widgets.
with st.expander('RESET'):
if st.button("Reset"):
st.session_state.q1_disabled = False
# Define disabled parameter.
user_answer = st.number_input("1 + 1", disabled=st.session_state.q1_disabled)
# Define disabled parameter.
if st.button("Check answer", disabled=st.session_state.q1_disabled):
if user_answer == 2:
st.session_state["score"] += 1
st.write("Correct! Score: " + str(st.session_state["score"]))
st.session_state.q1_disabled = True
# Sleep for 3 sec to see the message Correct! ....
time.sleep(3)
# Rerun the code from top to bottom to show the button
# and number input widgets in a disabled states.
st.experimental_rerun()
else:
st.write("Wrong! Score: " + str(st.session_state["score"]))
That is good! I know that as well, but for some reason I have to press it two times before it freezes, and then you can get 2 points but you should get 1.
Another approach without rerun, but using callback.
import streamlit as st
# Create a session variable to disable number input and
# button widgets when answer is correct.
if 'q1_disabled' not in st.session_state:
st.session_state.q1_disabled = False
# Define score session variable to keep track of score.
if "score" not in st.session_state:
st.session_state["score"] = 0
def cb(ans):
"""Check Answer button callback"""
if ans == 2:
st.session_state.q1_disabled = True
# Reset the disabled states of widgets.
with st.expander('RESET'):
if st.button("Reset"):
st.session_state.q1_disabled = False
# Define disabled parameter.
user_answer = st.number_input("1 + 1", disabled=st.session_state.q1_disabled)
# Define disabled parameter.
st.button("Check answer",
disabled=st.session_state.q1_disabled,
key='btn',
on_click=cb,
args=(user_answer,)
)
if st.session_state.btn:
if user_answer == 2:
st.session_state["score"] += 1
st.write("Correct! Score: " + str(st.session_state["score"]))
else:
st.write("Wrong! Score: " + str(st.session_state["score"]))