How to create a copy-to-clipboard button in streamlit?

Viewed 725

This discussion provides a workaround:

import streamlit as st
from bokeh.models.widgets import Button
from bokeh.models import CustomJS
from streamlit_bokeh_events import streamlit_bokeh_events
import pandas as pd

text_to_be_copied = "Some text"
copy_dict = {"content": text_to_be_copied}

copy_button = Button(label="Copy Text")
copy_button.js_on_event("button_click", CustomJS(args=copy_dict, code="""
    navigator.clipboard.writeText(content);
    """))

no_event = streamlit_bokeh_events(
    copy_button,
    events="GET_TEXT",
    key="get_text",
    refresh_on_update=True,
    override_height=75,
    debounce_time=0)

However, the button looks different than the usual streamlit buttons and cannot be used like those for example like this:

if st.button("Some button"):
    st.write("Some reaction")

Is there a way to modify the streamlit buttons such that they copy a text to the clipboard?

1 Answers

You must use pyperclip library to achieve what you want.

import pyperclip
text_to_be_copied = 'The text to be copied to the clipboard.'
pyperclip.copy(text_to_be_copied)
Related