如何在Streamlit的component.html中识别深色主题并动态设置文本颜色?
如何在Streamlit中根据主题动态调整component.html的文本颜色
完全可以通过代码识别Streamlit的主题变化,进而动态调整component.html中的文本颜色,具体实现方式如下:
- 识别当前主题:Streamlit会将主题信息存储在
st.session_state.theme中,其中st.session_state.theme.base直接标识当前是light(浅色)还是dark(深色)主题;也可以通过st.session_state.theme.backgroundColor等属性的RGB值判断明暗。 - 动态生成HTML样式:根据识别到的主题,为文本设置对应的颜色值,比如浅色主题用深色调文本,深色主题用浅色调文本。
修改后的示例代码:
import streamlit as st import streamlit.components.v1 as components # 获取当前主题 current_theme = st.session_state.get("theme", {}).get("base", "light") # 根据主题设置文本颜色 text_color = "rgb(81, 0, 12)" if current_theme == "light" else "rgb(230, 230, 230)" components.html( f'<html><body> \ <div style="color: {text_color}; font-size: 23px; font-family: \'Book Antiqua\';"> \ "This is a test message." \ </div> \ </body></html>' )
如果需要更精准的颜色匹配(比如和Streamlit主题的默认文本色完全一致),可以直接调用主题中的文本颜色属性:
# 获取主题默认文本颜色 text_color = st.session_state.theme.textColor components.html( f'<html><body> \ <div style="color: {text_color}; font-size: 23px; font-family: \'Book Antiqua\';"> \ "This is a test message." \ </div> \ </body></html>' )
这样当用户切换主题时,页面重新渲染后,component.html中的文本颜色会自动适配当前主题。
内容的提问来源于stack exchange,提问作者P V
相关产品推荐
相关产品推荐

