Если в вашем коде есть проблема, вероятно, она не в той части, которую вы вставили в вопрос. Я написал MWE вокруг предоставленного вами обратного вызова, и кажется, что он работает так, как вы намеревались:
Improvements for the callback
- The code below includes a bit improved callback
- The
prop_id
attribute of the items in the list dash.callback_context.triggered
is of the form component_id.component_property
. Therefore, if you want to check whether it was 'create_button'
that triggered the callback, you should compare against the part before the dot (or compare to 'create_button.n_clicks'
directly).
- Previously, only the first element in the list
dash.callback_context.triggered
was checked. You probably want to check against all the elements in the list, although in current version of dash it can only contain properties of single component: "is a length-1 list, unless two properties of a single component update simultaneously, such as a value and a timestamp or event counter." ( da sh .callback_context.triggered ) - Повышенная читаемость за счет удаления ненужное вложение операторов if, поскольку выполнение функции не будет продолжено после
return
.
Полный код
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
tab_div = html.Div(
dcc.Tabs(id='selection_tabs', value='tab-1', children=[
dcc.Tab(label='Tab one', value='tab-1'),
dcc.Tab(label='Tab two', value='tab-2'),
]))
app.layout = html.Div(children=[
html.H1(children='Test app'),
tab_div,
dcc.Input(id="text-input", type="text", placeholder=""),
html.Div(id='PRINTOUTPUT'),
html.Button('Click me', id='create_button')
])
@app.callback(Output('PRINTOUTPUT', 'children'),
[Input('create_button', 'n_clicks'),
Input('selection_tabs', 'value')],
[State('text-input', 'value')])
def xyz(clicks, selected_tab, textinput):
#To determine if n_clicks is changed.
changed_ids = [p['prop_id'].split('.')[0] for p in dash.callback_context.triggered]
button_pressed = 'create_button' in changed_ids
if not button_pressed:
return ""
if textinput == "": #Do nothing if button is clicked and input num is blank.
return "No input"
#Do some calculations based on the selected tab and input
return "Successful"
if __name__ == '__main__':
app.run_server(debug=True)