You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Dash框架中按钮添加图片失败的技术问询

问题排查与解决方案

按钮图片无法显示的核心原因是浏览器无法直接访问本地文件系统的绝对路径,Dash对静态资源有特定的加载规则,以下是两种可行的解决方法:

方法一:使用默认assets文件夹(推荐)

Dash默认会从项目根目录下的assets文件夹加载静态资源,步骤如下:

  1. 在你的Dash项目根目录创建名为assets的文件夹,将b.jpeg图片放入其中。
  2. 修改html.Img的src属性为图片文件名,同时可通过style调整图片尺寸适配按钮:
from dash import Dash, dcc, html, Input, Output, State
app = Dash(__name__)
app.layout = html.Div([
    html.Div(dcc.Input(id='input-on-submit', type='text')),
    html.Button(
        children=[html.Img(src='b.jpeg', style={'height': '30px', 'width': '30px'})],
        id='submit-val',
        n_clicks=0
    ),
    html.Div(id='container-button-basic', children='Enter a value and press submit')
])

@app.callback(
    Output('container-button-basic', 'children'),
    Input('submit-val', 'n_clicks'),
    State('input-on-submit', 'value')
)
def update_output(n_clicks, value):
    return f'The input value was "{value}" and the button has been clicked {n_clicks} times' 

if __name__ == '__main__':
    app.run_server(debug=True)

方法二:配置自定义静态资源路径

如果不想使用assets文件夹,可通过Dash初始化参数指定自定义静态资源目录:

  1. 在初始化app时设置static_folder为你的图片所在目录:
app = Dash(__name__, static_folder='/home/Documents/web')
  1. 将html.Img的src改为'/static/b.jpeg'(Dash会自动将static_folder映射到/static路径):
html.Img(src='/static/b.jpeg', style={'height': '30px', 'width': '30px'})

额外注意事项

  • 确保图片文件名大小写与代码中一致(Linux系统区分大小写)。
  • 若图片仍不显示,可检查浏览器控制台的网络请求,确认资源是否返回404错误,排查路径是否正确。

内容的提问来源于stack exchange,提问作者sruthi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 05:00:58