How To Add A Customized Background In Streamlit In Python.


Hello guys welcome to our blog Today in this we can see about how to add a customised background in your Streamlit app in two different way.

  1. Add Customised background from online
  2. Add Customised background from your computer
Add Customised background from online:

     In this we can add the background using the online url for your Streamlit app just put the code below and change the url of image(which you want to set as a background)

Import Streamlit as st

def add_bg_from_url():
    st.markdown(
         f"""
         <style>
         .stApp {{
             background-image: url("https://cdn.pexel.com/photo/272-373-37.jpg");
             background-attachment: fixed;
             background-size: cover
         }}
         </style>
         """,
         unsafe_allow_html=True
     )

add_bg_from_url() 

Using the above code we can set background from online (URL)


Add Customised background from your computer:

  In this we can add the background form your computer using a package base64 for your Streamlit app just put the code below and change the image path in the function (which you want to set as a background) add_bg_from_local("image.png")

import base64
def add_bg_from_local(image_file):
    with open(image_file, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read())
    st.markdown(
    f"""
    <style>
    .stApp {{
        background-image: url(data:image/{"png"};base64,{encoded_string.decode()});
        background-size: cover
    }}
    </style>
    """,
    unsafe_allow_html=True
    )
add_bg_from_local('you_bg.png')