Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streamlit button works only once

Tags:

streamlit

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)
like image 560
Sherif Shawkat Avatar asked Dec 04 '22 17:12

Sherif Shawkat


2 Answers

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.

like image 192
anonymoose Avatar answered Jan 10 '23 05:01

anonymoose


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)
like image 44
lakadibo Avatar answered Jan 10 '23 05:01

lakadibo