You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何捕获Streamlit文本框的Command+Enter触发动作?

解决Streamlit TextArea快捷键触发提交的问题

方法1:用Streamlit表单(推荐,原生支持)

Streamlit的表单组件自带输入框快捷键提交功能,Mac下按Command+Enter、Windows下按Ctrl+Enter就能直接触发表单提交,完全匹配你的需求,而且不用写额外代码,稳定性高。

修改后的代码:

with st.container():
    # 用表单包裹输入框和按钮
    with st.form(key='question_form'):
        query = st.text_area("Ask a question here:", height=100, key="query_text")
        # 表单提交按钮,替代普通button
        submit_btn = st.form_submit_button(label='Submit')
    
    # 触发逻辑和之前完全一致
    if submit_btn:
        with st.spinner('Fetching Answer...'): 
            response = custom_qa.qa.run(query)
            # 这里可以添加结果展示,比如st.write(response)

这样用户在text_area里按快捷键时,会自动执行和点击按钮一样的逻辑。

方法2:自定义JS监听键盘事件

如果不想用表单,可以注入JS代码监听快捷键,模拟点击提交按钮。这种方法需要依赖Streamlit的DOM结构,版本更新后可能需要调整选择器。

代码示例:

import streamlit as st

with st.container():
    query = st.text_area("Ask a question here:", height=100, key="query_text")
    button = st.button("Submit", key="button")

# 注入JS监听快捷键事件
st.components.v1.html("""
<script>
// 定位到text_area和提交按钮
const textArea = window.parent.document.querySelector('[data-testid="stTextArea"][aria-label="Ask a question here:"]');
const submitBtn = window.parent.document.querySelector('[data-testid="stButton"][aria-label="Submit"]');

textArea.addEventListener('keydown', function(e) {
    // 判断是否按下Command+Enter(Mac)或Ctrl+Enter(Windows)
    if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
        e.preventDefault(); // 阻止默认的换行行为
        submitBtn.click(); // 触发按钮点击
    }
});
</script>
""", height=0)

# 原有逻辑保持不变
if button:
    with st.spinner('Fetching Answer...'): 
        response = custom_qa.qa.run(query)
        st.write(response)

内容的提问来源于stack exchange,提问作者Baktaawar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 02:45:25