Hi guys,
im new to Streamlit, and I want to create three buttons, each one with differen image as backgroud, the code of doing that i found is first convert the image to base64, then apply it to the button style below:
button_style = f"""
<style>
div.stButton > button {{
background: url(data:image/png;base64,{encoded_image}) no-repeat;
background-size: cover;
background-position: center;
height: 16em;
width: 24em;
box-shadow: 10px 10px 5px grey;
margin: 15px;
}}
</style>
"""
st.markdown(button_style, unsafe_allow_html=True)
however, it seems only the last โencoded_imageโ is working, that my three buttons showing the same background image, can anyone tell me how to properly set the correct image background? below is my full code for this one:
import streamlit as st
import pandas as pd
import re
import os
import base64
def display_image_csv_viewer(file_path):
st.set_page_config(layout='wide')
all_files = search_file(file_path)
image_files = [file for file in all_files if file.find('twitter_image') != -1]
paper_files = [file for file in all_files if file.endswith('.csv')]
encoded_images = {}
for i, image_file in enumerate(image_files):
with open(image_file, "rb") as f:
encoded_image = base64.b64encode(f.read()).decode()
encoded_images[f"button{i + 1}"] = encoded_image
# Create buttons dynamically
cols = st.columns(len(encoded_images))
selected_button_key = st.session_state.get('selected_button_key')
for i, button_key in enumerate(encoded_images.keys()):
with cols[i]:
encoded_image = encoded_images[button_key]
# Apply new button style
button_style = f"""
<style>
div.stButton > button {{
background: url(data:image/png;base64,{encoded_image}) no-repeat;
background-size: cover;
background-position: center;
height: 16em;
width: 24em;
box-shadow: 10px 10px 5px grey;
margin: 15px;
}}
</style>
"""
st.markdown(button_style, unsafe_allow_html=True)
if selected_button_key == button_key:
st.button('', key=button_key, on_click=None)
else:
if st.button('', key=button_key):
selected_button_key = button_key