【发布时间】:2020-07-03 08:06:46
【问题描述】:
我想构建一个不时更新的 DataTable。每次发生这种情况时,表都应该从 csv 文件中获取数据。为了做到这一点,我构建了一个生成并返回表的函数。这有效,在第二次更新后 - 但我生成的第一个表仍然存在,因此我最终得到一个表做我想要的但另一个只是留下的表......:
The one on top is the second one, which updates. The one in the bottom is the on i generated first,
这是我的代码:
import random
import dash
from dash.dependencies import Input, Output, State
import dash_table
import dash_html_components as html
import pandas as pd
df = pd.read_csv('.../dummy2_csv.csv')
def maketable(dataf):
tab = html.Div([dash_table.DataTable(
id='adding-rows-table',
editable=True,
data=dataf.to_dict('rows'),
columns=[{'name': i, 'id': i} for i in dataf.columns])])
return tab
app = dash.Dash(__name__)
app.layout = html.Div([
html.Div(id='my-div'),
maketable(df),
html.Button('+', id='editing-rows-button', n_clicks=0),
html.Button('update', id='btn-save', n_clicks=0)
])
@app.callback(
Output(component_id='my-div', component_property='children'),
[Input('btn-save', '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-save' in changed_id:
df2 = pd.DataFrame(data)
for col in df2.columns:
# new values
df2[col].values[:] = random.randint(0,9)
df2.to_csv('.../dummy2_csv.csv', encoding='utf-8', index=False)
return maketable(df2)
@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)
提前感谢您的帮助!
最好的,t。
【问题讨论】:
标签: python callback plotly-dash