Streamlit: pass the widget input to its own callback
Asked Answered
H

2

11

I'd like to capture a text in a streamlit text_area widget (for instance, but any widget that produces input should work the same), and pass the captured text to the callback. How could I do that ? (if it's possible).

So far I've tried:

import streamlit as st

def callback(string):
    print(string) # do something using a string here

and then either

text_input = st.text_area("Enter a text", key="input_text", 
                          on_change=callback,
                          args=(text_input,))

# text_input does not exist

or

text_input = st.text_area("Enter a text", key="input_text", 
                          on_change=callback,
                          args=(st.session_state.input_text,))

# session_state.input_text is not initialized

both result in errors.

My basic usage is e.g.:

  • add a user comment on a log-like file in the back
  • append a string to a list in the back

I found a workaround

input_text= st.text_area("Enter a text", key="input_text")

if input_text!= st.session_state.input_text:
     callback(input_text)
     st.session_state.input_text = input_text
st.button("Callback", on_click=callback(input_text))

following a tutorial on towardsdatascience but I'mn not entirely satisfied with it, as it has two widgets that may compete with each other while I need only one.

Heedless answered 10/5, 2022 at 8:17 Comment(0)
C
16

Do like this. Notice the press cntrl+enter to apply.

Code
def proc():
    st.write(st.session_state.text_key)

st.text_area('enter text', on_change=proc, key='text_key')
Output

enter image description here

Chanachance answered 10/5, 2022 at 9:34 Comment(0)
C
4
st.button("Callback", on_click=callback(input_text))

didn't work for me but the following did

def waschanged(key):
    st.info(st.session_state[key])

setBrightness = st.slider("Brightness", -10, 10, 0, step=1, key="Brightness", on_change=waschanged, args=("Brightness",))

This prints the latest changed variable

Chestonchest answered 7/7, 2023 at 0:6 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.