我正在使用新的多页功能,并且想要设计我的多页应用程序的样式,并将带有标题的徽标放在页面导航的顶部/之前。
这是在以下目录结构中Python 3.9测试的一个小示例:streamlit==1.11.1
/Home.py
/pages/Page_1.py
/pages/Page_2.py
Run Code Online (Sandbox Code Playgroud)
Home.py:
import streamlit as st
st.sidebar.markdown(
"My Logo (sidebar) should be on top of the Navigation within the sidebar"
)
st.markdown("# Home")
Run Code Online (Sandbox Code Playgroud)
Page_1.py:
import streamlit as st
st.markdown("Page 1")
Run Code Online (Sandbox Code Playgroud)
Page_2.py:
import streamlit as st
st.markdown("Page 2")
Run Code Online (Sandbox Code Playgroud)
我可以使用以下命令运行:
$ streamlit run Home.py
Run Code Online (Sandbox Code Playgroud)
有什么办法可以做到这一点吗?欢迎任何提示!
最美好的祝愿,科德
小智 11
一种选择是通过 CSS 来实现,函数如下:
def add_logo():
st.markdown(
"""
<style>
[data-testid="stSidebarNav"] {
background-image: url(http://placekitten.com/200/200);
background-repeat: no-repeat;
padding-top: 120px;
background-position: 20px 20px;
}
[data-testid="stSidebarNav"]::before {
content: "My Company Name";
margin-left: 20px;
margin-top: 20px;
font-size: 30px;
position: relative;
top: 100px;
}
</style>
""",
unsafe_allow_html=True,
)
Run Code Online (Sandbox Code Playgroud)
基于 Zachary Blackwoods 的答案和Streamlit 论坛的答案,还提供以字符串编码的本地文件,我在我的 中提出了这个解决方案Home.py:
import base64
import streamlit as st
@st.cache(allow_output_mutation=True)
def get_base64_of_bin_file(png_file):
with open(png_file, "rb") as f:
data = f.read()
return base64.b64encode(data).decode()
def build_markup_for_logo(
png_file,
background_position="50% 10%",
margin_top="10%",
image_width="60%",
image_height="",
):
binary_string = get_base64_of_bin_file(png_file)
return """
<style>
[data-testid="stSidebarNav"] {
background-image: url("data:image/png;base64,%s");
background-repeat: no-repeat;
background-position: %s;
margin-top: %s;
background-size: %s %s;
}
</style>
""" % (
binary_string,
background_position,
margin_top,
image_width,
image_height,
)
def add_logo(png_file):
logo_markup = build_markup_for_logo(png_file)
st.markdown(
logo_markup,
unsafe_allow_html=True,
)
add_logo("img/my_logo.png")
st.markdown("# Home")
Run Code Online (Sandbox Code Playgroud)
@Zachary Blackwood:请随意将其放入您的答案中,我将删除我的答案。
希望它能帮助别人!