我正在使用python dash,我想创建一个菜单/表单列表,这些菜单/表单可以通过单击按钮来动态扩展和缩小。添加新表单/菜单应将另一个相同的表单添加到页面(表单/菜单列表)。
下面的代码允许添加/删除包含多个破折号核心组件的附加div,但是,每当我在其中一个下拉列表中选择一个选项或在其中一个输入字段中输入任何内容时,我选择或输入的内容将再次消失。
import dash
import dash_core_components as dcc
import dash_html_components as html
step = html.Div(
children=[
"Menu:",
dcc.Dropdown(options=[{'label': v, 'value': v} for v in ['option1', 'option2', 'option3']]),
dcc.Input(placeholder="Enter a value ...", type='text', value='')
])
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
div_list = [step]
app.layout = html.Div(
children=[
html.H1(children='Hello Dash'),
html.Div(children=div_list, id='step_list'),
html.Button('Add Step', id='add_step_button', n_clicks_timestamp='0'),
html.Button('Remove Step', id='remove_step_button', n_clicks_timestamp='0')])
@app.callback(
dash.dependencies.Output('step_list', 'children'),
[dash.dependencies.Input('add_step_button', 'n_clicks_timestamp'),
dash.dependencies.Input('remove_step_button', 'n_clicks_timestamp')],
[dash.dependencies.State('step_list', 'children')])
def add_step(add_ts, remove_ts, div_list):
add_ts = int(add_ts)
remove_ts = int(remove_ts)
if add_ts > 0 and add_ts > remove_ts:
div_list += [step]
if len(div_list) > 1 and remove_ts > add_ts:
div_list = div_list[:-1]
return div_list
if __name__ == '__main__':
app.run_server(debug=True)有人能给我解释一下我哪里做错了吗?
非常感谢!
发布于 2019-05-23 05:22:42
Dash组件需要指定id,以便在回调后保存值。
这个使用随机ids将step生成为函数的示例解决了这个问题:
import dash
import dash_core_components as dcc
import dash_html_components as html
import numpy as np
def step():
return html.Div(
children=[
"Menu:",
dcc.Dropdown(options=[{'label': v, 'value': v} for v in ['option1', 'option2', 'option3']],id=str(np.random.randn())),
dcc.Input(placeholder="Enter a value ...",id=str(np.random.randn()))
])
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div(
children=[
html.H1(children='Hello Dash'),
html.Div(children=[step()], id='step_list'),
html.Button('Add Step', id='add_step_button', n_clicks_timestamp=0),
html.Button('Remove Step', id='remove_step_button', n_clicks_timestamp=0)])
@app.callback(
dash.dependencies.Output('step_list', 'children'),
[dash.dependencies.Input('add_step_button', 'n_clicks_timestamp'),
dash.dependencies.Input('remove_step_button', 'n_clicks_timestamp')],
[dash.dependencies.State('step_list', 'children')])
def add_step(add_ts, remove_ts, div_list):
add_ts = int(add_ts)
remove_ts = int(remove_ts)
if add_ts > 0 and add_ts > remove_ts:
div_list += [step()]
if len(div_list) > 1 and remove_ts > add_ts:
div_list = div_list[:-1]
return div_list
if __name__ == '__main__':
app.run_server(debug=True)https://stackoverflow.com/questions/52905569
复制相似问题