St.write - typewritter

What s the best way to use a typewriter effect on Streamlit? Mean it writes word by word or letter by letter rather than all at once? Thanks

I don’t think there is a native way to get that effect. But you can bring something that makes that effect and integrate it to using streamlit components API. Here is an example from codepen integrated in a streamlit app:

codepen_typewrite

The gist of the code is that the CSS and JS bits from codepen are stored in separate files that python reads and assemble into a big HTML string. That is then passed to the st.components.v1.html to show it in the app.

import streamlit as st

def typewrite(text:str):
    with open("assets/codepen.css") as f:
        # The CSS from the codepen was stored in codepen.css
        css = f.read()

    with open("assets/codepen.js") as f:
        # The JS from the codepen was stored in codepen.js
        js = f.read()

    html = f"""
    <!DOCTYPE html>
    <head>
    <style>
        {css}
    </style>
    </head>
    <body>
        <p id="typewrite" data-content="">{text.upper()}</p>
        <script>
            {js}
        </script>
    </body>
    </html>
    """
    return html

text = st.text_input("Write a sentence", max_chars=150)
typewrited = typewrite(text)
st.components.v1.html(typewrited, height=400, scrolling=True)
1 Like

Hey @bwilliams12117,
Here is a simple yet effective typewriter effect for streamlit:

def typewriter(text: str, speed: int):
    tokens = text.split()
    container = st.empty()
    for index in range(len(tokens) + 1):
        curr_full_text = " ".join(tokens[:index])
        container.markdown(curr_full_text)
        time.sleep(1 / speed)

#Sample Example
text = "This is an example of streamlit text with typewriter effect :)"
speed = 10
typewriter(text=text, speed=speed)
2 Likes

Since version 1.31.0, there is st.write_stream: