Form inside a loop for image sorting app

I have a folder if png images, and for each I wish to keep or discard them. I created a simple app with a form below, but am unsure how to iterate over the list of images. Advice appreciated!

import streamlit as st
import pandas as pd
import glob as glob

file_pattern = st.text_input('Glob file pattern to match', 'images/*.png')
image_list = glob.glob(file_pattern)
st.write(f"Found {len(image_list)} images")

for image_id in range(len(image_list)):
    with st.form("annotation_form"):
        st.image(image_list[image_id], caption = f"{image_list[image_id]}", use_column_width=True)
        choice = st.radio("Choose", ("keep", "discard"))

        # Every form must have a submit button.
        submitted = st.form_submit_button("Submit")
        if submitted:
            st.write("choice", choice)
        
## Put choices in dataframe, save when done

I’m not sure what you mean by

What problem are you running into here, the images don’t show?

Sorry the issue with the form in a loop:

I guess I need to use session state. Actually found an app which addresses my use case :slight_smile: https://github.com/lit26/streamlit-img-label

In the case of the key error, you are creating a new widget each time, but because of how Streamlit works it seems like you are “writing over it”, but they are actually getting orphaned in the background. Then, Streamlit doesn’t know which one you are referring to when you say with st.form().

The solution to this is to add a key argument with a unique identifier. Something like:

with st.form("annotation_form", key = image_id)

Best,
Randy

1 Like

Thanks that resolves the issue!