如何在streamlit中按Enter键后清除输入字段?

问题描述 投票:0回答:1

我有一个 Streamlit 应用程序,我想在其中获取用户输入并稍后使用它。但是,我还想在用户按 Enter 后立即清除输入字段。我在网上查了一下,似乎我需要将回调函数传递给

text_input
,但我无法使其工作。我尝试了几个不同的版本,但都没有达到我的预期。

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)

期望将输入保存到

my_text
并随后清除该字段。

我查看了有关清除文本输入的类似问题herehere,但它们与我的案例无关,因为我希望输入字段自动清除,而这些案例讨论使用单独的按钮。我该如何让它发挥作用?

python widget user-input streamlit
1个回答
0
投票

您可以稍微调整@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)

输出:

© www.soinside.com 2019 - 2024. All rights reserved.