绘图破折号:在降价文本中显示变量



我是Dash和Plotly生态系统的新手,几天前开始构建基于Web的仪表板。

下面是一段代码:

import dash
import dash_html_components as html
import dash_core_components as dcc

# initialize the application
app = dash.Dash()
# define the layout of the app
app.layout = html.Div([
# add a date range selector
dcc.DatePickerRange(
id = 'my-date-picker-range',
min_date_allowed = dt(2010,1,4),
max_date_allowed = dt(2020, 12, 31),
initial_visible_month = dt(2020, 5, 23)
),
html.Div(id = 'output-container-date-picker-range'),
# add some markdown text
dcc.Markdown(f'''
This report covers the time period spanning {start_date} to {end_date}.
'''),
])

@app.callback(
dash.dependencies.Output('output-container-date-picker-range', 'children'),
[dash.dependencies.Input('my-date-picker-range', 'start_date'),
dash.dependencies.Input('my-date-picker-range', 'end_date')])
app.run_server(debug = True)

我正在尝试在降价文本中显示start_dateend_date变量(使用f string(。 不幸的是,我收到以下错误消息:

NameError: name 'start_date' is not defined

是否可以在降价文本中包含变量输出? 谢谢!

您正在使用装饰器 (@app.callback(,但未将其附加到要执行的函数。您需要将装饰器附加到负责更新正确div 的函数。

我认为您最好的选择是坚持使用文档。

这给出了与您想要的结果类似的结果:

import dash
import dash_html_components as html
import dash_core_components as dcc
from datetime import datetime as dt
# initialize the application
app = dash.Dash()
# define the layout of the app
app.layout = html.Div([
# add a date range selector
dcc.DatePickerRange(
id = 'my-date-picker-range',
min_date_allowed = dt(2010,1,4),
max_date_allowed = dt(2020, 12, 31),
initial_visible_month = dt(2020, 5, 23)
),
html.Div(id = 'output-container-date-picker-range'),
])
@app.callback(
dash.dependencies.Output('output-container-date-picker-range', 'children'),
[dash.dependencies.Input('my-date-picker-range', 'start_date'),
dash.dependencies.Input('my-date-picker-range', 'end_date')])
def update_output_div(start_date, end_date):
return f"This report covers the time period spanning {start_date} to {end_date}"
app.run_server(debug = True)

最新更新