Write_stream and text_area/code

Hello,
I would like to ask if there is any way to use write_stream in text_area or code component?
Suppose when the button is clicked, so that text simulating typing is entered into the text_area/code?
Pseudocode:

def generate_description():
    st.write_stream('test text')

st.text_area('description', value='')
st.button('generate description', on_click=generate_description)

I tried to achieve this through st.session_state, but unfortunately the text_area is updated when all the text is added.
Any help would be appreciated

test-GoogleChrome2024-07-1914-34-06-ezgif.com-crop (1)

You can simulated the stream effect by updating the text area for each word.

import streamlit as st
import time

# Define the text to simulate typing
_LONG_TEXT = """Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
"""

# Define a generator function to yield text incrementally
def stream_text():
    current_text = ""
    for char in _LONG_TEXT:
        current_text += char
        yield current_text
        time.sleep(0.01)  # Adjust the speed of typing

# Define the function to update the text area
def generate_description():
    text_generator = stream_text()
    text_area = st.empty()
    for text in text_generator:
        text_area.text_area('Description', value=text, height=150)
        time.sleep(0.01)  # Adjust the speed of typing

# Ensure the session state has a key for description
if 'description' not in st.session_state:
    st.session_state.description = ''

# Display the text area with the current session state value
text_area_placeholder = st.empty()

# Button to start the typing simulation
if st.button('Generate Description'):
    generate_description()

1 Like

Thank you very much! This solves my problem - I was trying to achieve something similar, but somewhere I must have had a mistake in the logic. Thank you again!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.