Capture 'ENTER' key press event in text_input


I want to capture the ‘ENTER’ keypress event in text_input. I could not find any example or documentation for this. Below is something I was trying to achieve using Streamlit:

How to specify event on ‘ENTER’ key?

text = st.text_input(“User pressed enter”)

How to detect ‘ENTER’ key press?

if user_presses_enter_key:
print(“Execute this code on ENTER keypress event”

Currently, I have added a separate button which the user has to click every time for the input, but I want this to happen when the user presses the ‘ENTER’ key.

Appreciate any help in advance.

Hello @Sushant, welcome to the forum!

Streamlit does not work with event bindings. In fact, each time you interact with your app (press Enter on your text_input for example), the whole script reruns.

So, what is your use-case exactly?

If you want to execute some code when your text_input contains something, it’s as simple as this:

import streamlit as st

value = st.text_input("Some input")

if value:
    st.write("There is some value. Processing...")
    # Some code
1 Like

Hi @synode, thanks for your quick reply.

My use-case is a simple search app, where the user should be able to use ‘Enter’ key press to input the query and display the results other than clicking a button as well. I have done this with a hack which works fine for now for both the cases, but wanted to do a few things on other keypress events as well. Thanks for the clarification on event bindings.


prev_qry = ""
user_query = st.text_input(label="Enter query")
if st.button('Search') or (prev_qry != user_query):
    prev_qry = user_query
    # Display search results for user_query

My other queries were with st.dataframe. I guess I will open a different topic for that. Thank you.

I don’t see your solution as a hack per se. Your if statement describes exactly what you want to do, and one of Streamlit goals is to allow such logic flows.

What other keypress events you plan to implement?

I wanted to use other key press events (backspace, shift…) to trigger some functionality, but I can do that in an alternative way. Thanks for the help. I am currently trying the dataframe issue which I have raised here Adjust dataframe column width. Would really appreciate your help on that.