Plotly Dash:如何重置 dash-html.button 的 "n_clicks" 属性?

Plotly Dash: How to reset the "n_clicks" attribute of a dash-html.button?

我在 plotly/dash 中有一个基本数据表。我的目标是在按下上传按钮后上传(或为了示例而打印...)。

问题是,我不知道如何将按钮的 n_clicks 属性恢复为零。所以发生的事情是,在我第一次点击按钮后,只要有什么变化(添加的行或数字 changed/added),它就会连续打印,但我想要的是它只在我点击按钮时打印一次。

这是代码:

import dash
from dash.dependencies import Input, Output, State
import dash_table
import dash_daq as daq

import dash_core_components as dcc
import dash_html_components as html
import pandas as pd

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']


df = pd.read_csv('.../dummy_csv.csv')


app = dash.Dash(__name__)

app.layout = html.Div([
    html.Div(id='my-div'),

    dash_table.DataTable(
        id='adding-rows-table',
        style_data={
            'whiteSpace': 'normal',
            'height': 'auto'
        },
        style_table={
            'maxHeight': '800px'
            , 'overflowY': 'scroll'
        },
        columns=[
            {'name': i, 'id': i} for i in df.columns
        ],
        data=df.to_dict('records'),
        editable=True,
        row_deletable=True

    ),

    html.Button('+ Row', id='editing-rows-button', n_clicks=0),

    html.Button('Update', id='btn-nclicks-1', n_clicks=0 ),

])


@app.callback(
    Output(component_id='my-div', component_property='children'),
    [Input('btn-nclicks-1', 'n_clicks'), Input('adding-rows-table', 'data')]
)
def update_output_div(n_clicks, data):
    if n_clicks > 0:
        print(data)
        # n_clicks = 0
        # return n_clicks

    else:
        print("else loop")


@app.callback(
    Output('adding-rows-table', 'data'),
    [Input('editing-rows-button', 'n_clicks')],
    [State('adding-rows-table', 'data'),
     State('adding-rows-table', 'columns')])
def add_row(n_clicks, rows, columns):
    if n_clicks > 0:
        rows.append({c['id']: '' for c in columns})
    return rows


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

这是 CSV:

a,b,c,d
1,1,5,1
2,2,5,1
2,33,6,2
3,4,6,2

而 this 是“错误”输出。

您可以使用 dash.callback_context 属性 仅在点击次数发生变化时触发回调,而不是在第一次点击后触发回调,请参阅“确定哪个按钮已更改 callback_context" 在 Dash 文档中:https://dash.plotly.com/dash-html-components/button。以下是如何更新回调的示例。

@app.callback(Output(component_id='my-div', component_property='children'),
    [Input('btn-nclicks-1', 'n_clicks'), Input('adding-rows-table', 'data')])
def update_output_div(n_clicks, data):

    changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]

    if 'btn-nclicks-1' in changed_id:

        print(data)
        # n_clicks = 0
        # return n_clicks

    else:

        print("else loop")