plotly dash,带有 2 个按钮输入和下拉输入的回调

plotly dash, callback with 2 button inputs and a dropdown input

我如何编写回调,以便在单击按钮 1 时执行 A;如果单击按钮 2,则执行 B;如果更改下拉值,执行 C?

import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash(__name__)
app.layout = html.Div([
        html.H1('initial', id = 'h1'),
        html.Button('to upper', id = 'upper button', n_clicks_timestamp = '0'),
        html.Button('to lower', id = 'lower button', n_clicks_timestamp = '0'),
        dcc.Dropdown(options = [{'value':s, 'label': s} for s in ['good','bad']], value = 'good', id = 'set string')
    ])

@app.callback(
         dash.dependencies.Output('h1', 'children'),
         [dash.dependencies.Input('upper button', 'n_clicks_timestamp'), 
          dash.dependencies.Input('lower button', 'n_clicks_timestamp'), 
          dash.dependencies.Input('set string', 'value')],
         [dash.dependencies.State('h1', 'children')]
    )
def update(upper, lower, newstring, currentstring):
    upper, lower = int(upper), int(lower)

    # ???
    # if dropdown changed, return newstring
    # ???

    if upper > lower:
        return currentstring.upper()
    if lower > upper:
        return currentstring.lower()

    return newstring

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

由于下拉列表没有 timestamp 属性,因此无法确定它是否是最新更改。

在您的回调中是否需要多次按下按钮?如果不是,当下拉菜单触发回调时,按钮将有 0 作为 n_clicks 和 None(或者还有 0,我不记得了)作为 n_clicks_timestamp。所以你可以推断下拉触发了回调,通过消除过程。

如果按钮被多次按下,您需要在包含按钮的 Div 的 children 属性 上创建另一个回调,并简单地重新实例化按钮,以便它们仍处于 0 n_clicks 和下一次回调的时间戳。