Update and use text inside a text_area

Hello there,

What I’m trying to do is to create a text_area that can be filled by hand or by a random value. I have two buttons one to insert a random number on the text area and another to write down the text inside it. This is the code:

st.write(
    """
# Biopsias classification demo
"""
)

print(st.session_state)

text_area = st.empty()

text = text_area.text_area("Text to analyze", "Write a number")

button1 = st.button("Random")
button2 = st.button("Run")

if button1:
    text = text_area.text_area("Text to analyze", str(random.random()))

if button2:
    st.write(text)

The random button works because it changes the value inside the text_area, but when I click on Run it always write “Write a number”.

1 Like

Hello @Javier_Jimenez_de_la , if I use the code this error comes up ,

NameError: name 'text_area_key' is not defined

Can you please copy and paste the code used, because clicking the ‘Random’ button, it doesn’t work as well .

Sorry, I have updated the code:

import random
import streamlit as st

st.write(
    """
# Biopsias classification demo
"""
)

print(st.session_state)

text_area = st.empty()

text = text_area.text_area("Text to analyze", "Write a number")

button1 = st.button("Random")
button2 = st.button("Run")

if button1:
    text = text_area.text_area("Text to analyze", str(random.random()))

if button2:
    st.write(text)

Hi @Javier_Jimenez_de_la ,

Thank you for the update. Since with every button click, Streamlit runs from the top, therefore you get "Write a number " as output while you click the |Run| Button. If I understand your trouble here, best possible workaround I believe, will be to give user the choice using Radio button i.e whether to generate a Random number or Type own number in the input box.

Also, I don’t get why you used print(st.session_state) in your code. Quick way to remeber the the randomly generated number can be written like this in your case,

if button1:
    text = text_area.text_area("Text to analyze", str(random.random()))
    st.session_state.catch_rand = text
    
# For running the stored one
if button2:
    st.write(st.session_state.catch_rand)

But in the above code, only the random button works, not if the user gives a number of his/her choice. So yeah, a little tweak with an extra widget might work here for you .

Cheers
Avra

1 Like

This question seems to be very similar to this question which contains a working example with explanation. The solution is basically to use session state and use a button to rerun the script again.