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

Streamlit代码块未显示复制到剪贴板按钮,如何添加该按钮?

在Streamlit中添加带复制按钮的文本框

你可以通过以下两种方式实现需求:

方法一:升级Streamlit启用内置复制按钮

Streamlit 1.20及以上版本中,st.code生成的代码块默认会显示复制按钮(部分主题下需确认设置)。先升级到最新版本:

pip install --upgrade streamlit

升级后直接使用st.code("Lorem Ipsum", language="text")即可,复制按钮会自动出现在代码块右上角。

方法二:自定义HTML+JS实现带复制按钮的文本框

如果升级后仍无复制按钮,或者需要自定义样式,可以用st.markdown结合HTML和JavaScript实现完全自定义的文本框:

import streamlit as st

def create_copyable_text(text, button_label="复制到剪贴板"):
    # 生成唯一ID避免页面元素冲突
    unique_id = f"copyable-text-{hash(text)}"
    # 构建带复制按钮的HTML结构
    custom_html = f"""
    <div style="position: relative; margin: 1.5rem 0;">
        <pre id="{unique_id}" style="background: #f6f8fa; padding: 1.2rem; border-radius: 6px; overflow-x: auto; white-space: pre-wrap;">{text}</pre>
        <button onclick="copyToClipboard('{unique_id}')" style="position: absolute; top: 0.7rem; right: 0.7rem; padding: 0.4rem 0.8rem; border: none; border-radius: 4px; background: #007bff; color: white; cursor: pointer; font-size: 0.9rem;">{button_label}</button>
    </div>
    <script>
        function copyToClipboard(elementId) {{
            const textElement = document.getElementById(elementId);
            navigator.clipboard.writeText(textElement.textContent).then(() => {{
                const btn = event.target;
                const originalLabel = btn.textContent;
                btn.textContent = '已复制';
                btn.style.background = '#28a745';
                setTimeout(() => {{
                    btn.textContent = originalLabel;
                    btn.style.background = '#007bff';
                }}, 2000);
            }}).catch(err => {{
                console.error('复制失败:', err);
            }});
        }}
    </script>
    """
    st.markdown(custom_html, unsafe_allow_html=True)

# 使用示例
create_copyable_text("Lorem Ipsum")

这段代码会生成一个带右上角复制按钮的文本框,点击按钮后会将文本复制到剪贴板,并显示“已复制”的提示,2秒后恢复原按钮文本。

内容的提问来源于stack exchange,提问作者João Areias

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:17:12