[Python] How can I add and remove fields dynamically?

Discussão em 'Python' iniciado por Stack, Julho 22, 2025.

  1. Stack

    Stack Membro Participativo

    I want to create a form to dynamically add and remove text_input fields. I am able to add a text_input when I click the "➕ Add field" button. However, I am unable to correctly remove a text_field.

    Every time I click on the "❌" button, the last added text_field is removed. However, I am unable to identify the occurrence of the button that is clicked on.

    import streamlit as st

    FIELDS = []
    DELETES = []

    if "fields_size" not in st.session_state:
    st.session_state.fields_size = 0
    st.session_state.fields = []
    st.session_state.deletes = []


    def add_field():
    st.session_state.fields_size += 1


    def delete_field():
    pass


    st.header("Dynamic form ⚒️")

    st.divider()

    # fields and types of the table
    for i in range(st.session_state.fields_size + 1):
    c1, c2 = st.columns(2)

    with c1:
    FIELDS.append(
    st.text_input(f"Field {i}", key=f"text{i}", label_visibility="visible"))

    with c2:
    DELETES.append(st.button("❌", key=f"delete{i}", on_click=delete_field))

    st.session_state.fields = FIELDS
    st.session_state.deletes = DELETES

    st.button("➕ Add field", on_click=add_field)

    Continue reading...

Compartilhe esta Página