Search code examples
pythonstreamlit

Streamlit clear fields of app do not work


I'm trying to implement a simple front with the streamlit, this front will have a area to input a question and two bottons, 1 to submit and execute some action in the question and 1 to clear all (question and answer - the action over the question), but I cannot clear all the fields. Here is my code:

app.py

import streamlit as st

def question_and_answer_app():
    st.title("Question and Answer App")

    question = st.text_input("Enter your question:")
    answer_placeholder = st.empty()

    col1, col2 = st.columns(2)  

    if col1.button("Submit"):
        reversed_question = question[::-1]
        answer_placeholder.text("Answer: " + reversed_question) 

    if col2.button("Clear"):
        question = ""
        answer_placeholder.empty()

if __name__ == "__main__":
    question_and_answer_app()

Can someone give me a possible way to solve this?


Solution

  • You can use the argument of "key" to locate the widget and remove the input text.

    import streamlit as st
    
    def clear_text():
        st.session_state["input"] = ""
    
    def question_and_answer_app():
        st.title("Question and Answer App")
    
        question = st.text_input("Enter your question:",  key="input")
        answer_placeholder = st.empty()
    
        col1, col2 = st.columns(2)
    
        if col1.button("Submit"):
            reversed_question = question[::-1]
            answer_placeholder.text("Answer: " + reversed_question)
    
        if col2.button("Clear", on_click=clear_text):
            answer_placeholder.empty()
    
    if __name__ == "__main__":
        question_and_answer_app()