我想知道是否可以动态更新initial_visible_month值。 例如:开始日期是 01/01/2024,结束日期是 31/21/2024。如果用户单击编辑开始日期,则initial_visible_month 值将变为start_date,如果用户单击编辑结束日期,则initial_visible_month 值将变为end_date。
我尝试使用回调,但我不知道当用户单击选择日期时如何获取输入。我想知道是否可以这样做,如果可以,我该怎么做。
可以使用回调和callback_context来更新
initial_visible_month
。 callback_context 是了解更新了哪个组件、属性和值以触发回调的关键。通过检查 ctx.args_grouping
中的数据,您可以确定 start_date 或 end_date 是否已编辑并获取新值。
请参阅回调上下文文档:https://dash.plotly.com/advanced-callbacks#defining-which-input-has-fired-with-dash.callback_context
这是一个演示应用程序,展示如何捕获更改的值并更新
initial_visible_month
。
from dash import Dash, html, dcc, Input, Output, State, ctx, no_update
# initialize the dash app as 'app'
app = Dash(__name__)
beginning_date = "2024-01-01"
ending_date = "2024-12-31"
# set up the app layout
app.layout = html.Div(
children=[
html.H1(children="Test Dashboard"),
html.P(id="my-paragraph"),
dcc.DatePickerRange(
id="my-date-picker-range",
start_date=beginning_date,
end_date=ending_date,
),
]
)
@app.callback(
Output("my-paragraph", "children"),
Output("my-date-picker-range", "initial_visible_month"),
State("my-date-picker-range", "initial_visible_month"),
Input("my-date-picker-range", "start_date"),
Input("my-date-picker-range", "end_date"),
)
def initial_visible_month_change(initial_visible_month, start_date, end_date):
triggered_id = ctx.triggered_id
if triggered_id == "my-date-picker-range":
for possible_triggers in ctx.args_grouping:
if possible_triggers["triggered"] is True:
if possible_triggers["property"] == "start_date":
initial_visible_month = start_date
elif possible_triggers["property"] == "end_date":
initial_visible_month = end_date
paragraph_text = f"initial_visible_month is {initial_visible_month} and set by {possible_triggers['property']}"
return (paragraph_text, initial_visible_month)
paragraph_text = f"initial_visible_month is {initial_visible_month}"
return (paragraph_text, no_update)
if __name__ == "__main__":
app.run(debug=True)
[1]: https://i.sstatic.net/rUGSMrnk.png