Streamlit button works only once
Asked Answered
G

3

5

I want to create a simple streamlit application, that when you press the button, it increments x and shows the new value of x.

However, it works only for the 1st time "x only shows the value 2 and doesn't increment"

import streamlit as st

x = 1
if st.button("Increment x"):
    x=x+1
    st.text(x)
Gothic answered 12/12, 2019 at 13:8 Comment(2)
I don't know streamlit, but algorithmically speaking, your if condition is tested only one time. You should try to add a loop before the if, so it can test your condition multiple times.Fatimahfatimid
Yes I know, but from streamlit it's not like that, for example if you use a "slider" it will be interactive without the need for a loop.Gothic
E
10

Streamlit re-runs the webpage script every time you make a change/interaction. So each time you click the button it resets x=1, then adds 1 to x.

Your button is working correctly, the issue is in the way streamlit handles events. You could try using st.cache to work around this, but I've never tried to replicate what you're aiming for.

Ensepulcher answered 13/12, 2019 at 0:46 Comment(4)
This is the correct answer. I'm adding on just to say that there is a concept of "state" on the near-term Streamlit roadmap, which will constitute the Right Way to save and build upon user input. (I am a Streamlit developer.)Damsel
Hi, @nthmost, can you provide an example of using caching to build a button with multiple click functionality?Medarda
Hi @AyushChaurasia -- You should try the SessionState example in the answer below instead of abusing st.cache. :) It won't be too long before Streamlit releases our next feature which we're simply calling "State", which will constitute the Right Way to do this. Thanks!Damsel
Agreed, please don't take my word as expert. I've only done some mild tinkering and cache was the only function I've learnt that has this type of ability.Ensepulcher
G
9

https://gist.github.com/tvst/036da038ab3e999a64497f42de966a92

Hey, this package worked wonders for me.

Download the code into the same folder you're working on and boom:

import SessionState

ss = SessionState.get(x=1)
    
if st.button("Increment x"):
    ss.x = ss.x + 1
    st.text(ss.x)
Gurtner answered 19/8, 2020 at 22:35 Comment(1)
Since I uploaded this, Streamlit has added their own version: docs.streamlit.io/en/stable/add_state_app.html.Gurtner
S
1

Streamlit's session state makes it possible to increment a value with the click of a button.

import streamlit as st

btn = st.button("Press Me")

if btn:
    if 'x' in st.session_state.keys():
        st.session_state['x']=st.session_state['x']+1
    else:
        st.session_state['x']=1

if 'x' in st.session_state.keys():
    st.write(st.session_state['x'])

X will increment by 1 for each button click.

Selfimprovement answered 24/1, 2023 at 18:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.