Search code examples
pythonwidgetuser-inputstreamlit

How to clear input field after hitting Enter in streamlit?


I have a streamlit app where I want to get user input and use it later. However, I also want to clear the input field as soon as the user hits Enter. I looked online and it seems I need to pass a callback function to text_input but I can't make it work. I tried a couple different versions but neither works as I expect.

import streamlit as st

def clear_text():
    st.session_state.my_text = ""

# This version doesn't clear the text after hitting Enter.
my_text = st.text_input("Enter text here", on_change=clear_text)

# This version clears the field but doesn't save the input.
my_text = st.text_input("Enter text here", on_change=clear_text, key='my_text')

st.write(my_text)

The expectation is to save the input into my_text and clear the field afterwards.

I looked at similar questions about clearing text input here and here but they're not relevant for my case because I want the input field to clear automatically while those cases talk about using a separate button. How do I make it work?


Solution

  • You can slightly adjust the solution provided by @MathCatsAnd :

    if "my_text" not in st.session_state:
        st.session_state.my_text = ""
    
    def submit():
        st.session_state.my_text = st.session_state.widget
        st.session_state.widget = ""
    
    st.text_input("Enter text here", key="widget", on_change=submit)
    
    my_text = st.session_state.my_text
    
    st.write(my_text)
    

    Output :

    enter image description here