Summary
I need to be able to clear the photos uploaded either using camera_input or file_uploader programatically via python.
I saw this other post: How to Clear uploaded images when using st.file_uploader, accepting multiple files and how to clear other outputs? - Streamlit Community Cloud - Streamlit. However it does not apply to me because I need to be able to perform different action depending on the photos uploaded. One of them being to clear all uploaded photos and retake.
Steps to reproduce
import streamlit as st
st.camera_input("Photo 1", key="photo1")
st.camera_input("Photo 2", key="photo2")
st.camera_input("Photo 3", key="photo3")
st.file_uploader("Upload your photos", key="photo4")
st.file_uploader("Upload your photos", key="photo5")
st.file_uploader("Upload your photos", key="photo6")
if st.button("Clear Photos"):
st.session_state.pop("photo1")
st.session_state.pop("photo2")
st.session_state.pop("photo3")
st.session_state.pop("photo4")
st.session_state.pop("photo5")
st.session_state.pop("photo6")
st.session_state.photo1 = None
st.session_state.photo2 = None
st.session_state.photo3 = None
st.session_state.photo4 = None
st.session_state.photo5 = None
st.session_state.photo6 = None
st.session_state
Expected behavior:
Reset all photos uploaded using both camera_input and file_uploaded. Including resetting the widget itself to its clean slate.
Actual behavior:
Although the st.session_state is reset, the widget is still displayed in it’s state before I change the session_state
Alternative Method tested
Alternative i tried to make use of st.empty(). Code as follows:
import streamlit as st
placeholder = st.empty()
with placeholder.container():
st.camera_input("Photo 1", key="photo1")
st.camera_input("Photo 2", key="photo2")
st.camera_input("Photo 3", key="photo3")
st.file_uploader("Upload your photos", key="photo4")
st.file_uploader("Upload your photos", key="photo5")
st.file_uploader("Upload your photos", key="photo6")
if st.button("Clear Photos"):
placeholder.empty()
for key, value in st.session_state.items():
if "photo" in key:
st.session_state.pop(key)
st.session_state
with placeholder.container():
st.camera_input("Photo 1", key="photo1")
st.camera_input("Photo 2", key="photo2")
st.camera_input("Photo 3", key="photo3")
st.file_uploader("Upload your photos", key="photo4")
st.file_uploader("Upload your photos", key="photo5")
st.file_uploader("Upload your photos", key="photo6")
However i run into another error as follows:
DuplicateWidgetID: There are multiple widgets with the same key='photo1'
.
To fix this, please make sure that the key
argument is unique for each widget you create.
Traceback:
File "C:\Users\User\Desktop\work\test\app.py", line 23, in <module>
st.camera_input("Photo 1", key="photo1")
Debug info
- Streamlit version: 1.21.0
- Python version: 3.9.16