使用Streamlit components.html()时图片下方文本不显示的问题排查
问题描述
我想用Streamlit的components.html()实现图片下方显示文本,但文本无法正常显示。以下是我的Streamlit代码和可正常运行的纯HTML代码,请问Streamlit代码存在什么问题?
我的Streamlit代码
import streamlit as st import streamlit.components.v1 as components components.html( '<html><body>' + '<a href="https://i.ibb.co/0j2mc7K/4-NPTEL.png" target="_blank" style="text-decoration: none;">' + '<img src="https://i.ibb.co/0j2mc7K/4-NPTEL.png" style="width:600px;">' + '<div style="color: rgb(81, 0, 12); font-size: 23px; font-family: \'Book Antiqua\';">Title</div>' + '<div style="margin-top: 15px; color: rgb(81, 0, 12); font-size: 17px; font-family: \'Book Antiqua\';">Some Description</div></a></body></html>' )
可正常运行的纯HTML代码
<html> <body> <a href="https://i.ibb.co/0j2mc7K/4-NPTEL.png" target="_blank" style="text-decoration: none;"> <img src="https://i.ibb.co/0j2mc7K/4-NPTEL.png" style="width:600px;"> <div style="color: rgb(81, 0, 12); font-size: 23px; font-family: 'Book Antiqua';"> Title </div> <div style="margin-top: 15px; color: rgb(81, 0, 12); font-size: 17px; font-family: 'Book Antiqua';"> Some Description </div> </a> </body> </html>
问题原因及解决方案
核心问题
- 组件高度不足:
components.html()默认高度仅为150px,你的图片高度加上下方文本的总高度远超这个值,导致文本被容器裁剪隐藏。 - HTML字符串转义与拼接冗余:手动转义HTML实体(如
<、")并拼接成单行字符串,不仅易出错,还增加维护成本。
修正后的代码
import streamlit as st import streamlit.components.v1 as components # 用多行三引号字符串编写HTML,无需手动转义,可读性更强 html_content = ''' <html> <body> <a href="https://i.ibb.co/0j2mc7K/4-NPTEL.png" target="_blank" style="text-decoration: none;"> <img src="https://i.ibb.co/0j2mc7K/4-NPTEL.png" style="width:600px;"> <div style="color: rgb(81, 0, 12); font-size: 23px; font-family: 'Book Antiqua';">Title</div> <div style="margin-top: 15px; color: rgb(81, 0, 12); font-size: 17px; font-family: 'Book Antiqua';">Some Description</div> </a> </body> </html> ''' # 设置足够的高度,确保图片和文本完整显示(可根据实际内容调整数值) components.html(html_content, height=700)
说明
- 改用Python多行三引号字符串直接编写HTML,省去手动转义HTML实体的步骤,代码更清晰,也避免了转义错误。
- 显式指定
height参数,给组件足够的空间显示所有内容,你可以根据图片实际高度和文本行数调整这个数值。
内容的提问来源于stack exchange,提问作者P V
相关产品推荐
相关产品推荐

