I've implemented the following design using Python Streamlit library.
When the user clicks button with plus icon, the page -ideally- should duplicate those two sliders covered by the blue area below.
However, the program does not yield the desired result. Firstly, it duplicates sliders to top, and secondly, it only duplicates for once. That is, if the button is clicked one more time, it does not duplicate sliders.
The page look like this when button is clicked:
And Here is the source code
import streamlit as st
import random
def create_component():
col_slider, col_add = st.columns(2)
with col_slider:
st.slider('Chapter 2 Method', 0, 4, key=random.randint(0, 1_000_000_000))
with col_add:
st.button("➕", help="See more", on_click=create_component, key=random.randint(0, 1_000_000_000), use_container_width=True)
st.slider("Chapter 2 Step", 0, 5, key=random.randint(0, 1_000_000_000))
if __name__ == '__main__':
# Pages
st.markdown("# Chapters and Methods")
st.sidebar.markdown("# Chapters and Methods")
slider1 = st.slider('Chapter 1 Method', 0, 3)
create_component()
What could be the reason for this and how to solve this problem. Plus, Streamlit may not be the most suitable library to implement this page but I don't have much time to learn a new library like Dash. Appreciate the help.
Callback functions execute as a prefix to the next page load. The widgets on top are what your callback function generated before the page loaded the rest. Furthermore, anything written on the page within a callback will be transiet; it will go away with the next page load.
If you want to repeat some widget a number of times, I recommend using a counter so you can pass the counter to explicitly create unique keys while keeping track of how many times you want to create them.
Here is a simple example:
import streamlit as st
def create_component(index):
cols = st.columns(2)
cols[0].slider('Slider', key=f'slider_a_{index}')
cols[1].slider('Slider', key=f'slider_b_{index}')
def add():
st.session_state.count += 1
if __name__ == '__main__':
if 'count' not in st.session_state:
st.session_state.count = 0
for i in range(st.session_state.count):
create_component(i)
st.button('Add', on_click=add)