如何使用Plotly Dash动态实现ListGroupItem的ListGroup



我想创建一个单词列表,在Dash应用程序中动态更新。为此,我想使用dash_bootstrap_components库中的ListGroup和ListGroupItem。

现在,如果ListGroup组件的children属性在输入和输出上都具有相同的类型,那么我的回调如下所示。然而,即使我的输出是一个列表,这显然是ListGroup的子级可以接受的类型,我从函数中读取的也是一个字典。类型为:{'rops':{'children':'sample_word'},'type':'ListGroupItem','namespace':'dash_bootstrap_components'。

那么问题是,我如何从ListGroup组件获得我在回调中返回的ListGroupItem组件列表作为输入?

import dash
import dash_bootstrap_components as dbc
import dash_html_components as html
app.layout = html.Div(children=[dbc.Row(dbc.ListGroup(id='list-group-items'))])
@app.callback([Output('list-group-items','children')],
[Input('input-domain-specific-words','value'),
Input('add-button','n_clicks'),
Input('delete-button','n_clicks'),
Input('reset-button','n_clicks')],
[State('list-group-items','children')])
def update_list(word,n_clicks_add,n_clicks_delete,n_clicks_reset,listChildren):
ctx = dash.callback_context
if not ctx.triggered:
raise dash.exceptions.PreventUpdate
else:
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
if button_id not in ['add-button','delete-button','reset_button']:
raise dash.exceptions.PreventUpdate
else:

if button_id == 'delete-button':
for item in listChildren:
if item.children == word:
listChildren.remove(item)

elif button_id == 'add-button':
listChildren.append(dbc.ListGroupItem(word))
elif button_id == 'reset-button':
listChildren = []
return [listChildren]

我希望这在以后可能会有用,即使只对我自己有用。答案是ListGroup组件确实返回了一个ListGroupItem组件列表,这些组件在回调中收集时是用JSON编写的。因此,每当您将ListGroupItem组件附加到ListGroup时,它都会被添加为ListGroupItem((元素,然而,当您将其取回时,它将读取为JSON。Bellow,我展示了我的代码中的一个例子:string1和string2以前已经添加到ListGroup组件中,但是,string3是在当前回调中添加的,因此它显示为ListGroupItem元素,而不是JSON。

[{'props': {'children': 'string1'}, 'type': 'ListGroupItem', 'namespace': 'dash_bootstrap_components'}, {'props': {'children': 'string2'}, 'type': 'ListGroupItem', 'namespace': 'dash_bootstrap_components'}, ListGroupItem('string3')]

我的特定回调的最终版本是:

@app.callback(
[Output('list-group-items','children')],
[Input('input-domain-specific-words','value'),
Input('add-button','n_clicks'),
Input('delete-button','n_clicks'),
Input('reset-button','n_clicks')],
[State('list-group-items','children')],
)
def updateWordList(word,n_clicks_add,n_clicks_delete,n_clicks_reset,listChildren):
ctx = dash.callback_context
if not ctx.triggered:
raise dash.exceptions.PreventUpdate
else:
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
if button_id not in ['add-button','delete-button','reset-button']:
raise dash.exceptions.PreventUpdate
else:
if not listChildren:
listChildren = []
if button_id == 'delete-button':
for item in listChildren:
if item['props']['children'] == word:
listChildren.remove(item)

elif button_id == 'add-button':
listChildren.append(dbc.ListGroupItem(word))
elif button_id == 'reset-button':
print('pressed reset')
return [[]]

return [listChildren]

最新更新