I am in situation where I need to assign the callback during the program’s running (for example in a callback).
I tried to assign the callback inside another callback, but it doesn’t work.
For example:
I start the view with this configuration:
And I defined a callback for the checklist object (the callback creates a dropdown object in case the checklist is marked and assign a callback for the dropdown object):
@app.callback(Output('testing_expand', 'children'),
[Input('testing_checklist', 'value')])
def test_callback(selected):
if selected is None:
raise dash.exceptions.PreventUpdate()
global testing_lst
returned = []
for select in selected:
obj = dcc.Dropdown(id=select, options=OptionsFormatWrapper(['option1']).formatted_values)
if select not in testing_lst:
app.callback(
Output(select, 'style'),
[Input(select, 'value')],
[State(select, 'id')]
)(temp)
testing_lst.append(select)
returned.append(obj)
return returned
The problem is when I perform change in the dropdown value the callback isn’t been called as expected.
@sjtrny
I have checklist and when item in this checklist is marked a dropdown should be appear. The problem is that the items in the checklist are not known before I execute the program (only during the running the user select this items).
Below I have an example where I have a checklist, when the checklist is marked a dropdown appears. Since you know what is in the checklist, you also then know what will appear in the dropdown. I don’t think you need dynamic callbacks to solve this problem.
Just create your dropdown ahead of time and show/hide it dynamically.
app = dash.Dash(__name__)
app.layout = html.Div([
dcc.Checklist(
id="city",
options=[
{'label': 'New York City', 'value': 'NYC'},
{'label': 'San Francisco', 'value': 'SF'}
],
value=[]
),
dcc.Dropdown(
id='nyc',
options=[
{'label': 'Empire State Building', 'value': 'esb'},
{'label': 'Central Park', 'value': 'central_park'},
],
value=None,
style={'display': 'none'}
),
html.Div(id='result')
])
# Hide the Dropdown
@app.callback(Output('nyc', 'style'), [Input('city', 'value')])
def toggle_dropdown(checklist):
if "NYC" in checklist:
return {'display': 'block'}
else:
return {'display': 'none'}
# Change something else based on checklist and dropdown
@app.callback(Output('result', 'children'), [Input('city', 'value'), Input('nyc', 'value')])
def toggle_dropdown(checklist, nyc):
return f"You selected {checklist} and {nyc}"
if __name__ == '__main__':
app.run_server(debug=True)