How to increment a function to a button?

i=i+1 and st.button() and st.write(i)

Hi @Alexey_Prikhodko, welcome to the Streamlit community!! :wave: :partying_face:

Our topic guide on how to Add State to your app walks you through examples of how to increment a variable count using the Session State API and callbacks:

https://docs.streamlit.io/en/stable/add_state_app.html

Example 2: Session State and Callbacks

import streamlit as st

st.title('Counter Example using Callbacks')
if 'count' not in st.session_state:
	st.session_state.count = 0

def increment_counter():
	st.session_state.count += 1

st.button('Increment', on_click=increment_counter)

st.write('Count = ', st.session_state.count)

Happy Streamlit’ing! :balloon:
Snehan

1 Like

Thanks for the quick reply. But I have a problem with increment button if two buttons are needed below code. There is a solution?:

if 'count' not in st.session_state:
    st.session_state.count = 0

def decrement_counter():
    st.session_state.count -= 1
st.button('decrement', on_click=decrement_counter())

def increment_counter():
    st.session_state.count += 1
st.button('Increment', on_click=increment_counter)

st.write('Count = ', st.session_state.count)

Hi @Alexey_Prikhodko,

Could you be a little more specific about exactly what issue you face?

If you meant you wanted two buttons --one to increment and another to decrement-- it is covered in Example 3: Use args and kwargs in Callbacks:

import streamlit as st

st.title('Counter Example using Callbacks with kwargs')
if 'count' not in st.session_state:
	st.session_state.count = 0

def increment_counter(increment_value=0):
	st.session_state.count += increment_value

def decrement_counter(decrement_value=0):
	st.session_state.count -= decrement_value

st.button('Increment', on_click=increment_counter,
	kwargs=dict(increment_value=5))

st.button('Decrement', on_click=decrement_counter,
	kwargs=dict(decrement_value=1))

st.write('Count = ', st.session_state.count)

Best,
Snehan

2 Likes

Biggggggggggg thank the solution:))

1 Like

Exactly what I was looking for! Thanks @snehankekre! :raised_hands:

Charly

1 Like