假设我有一个带有 20 个参数的模型,并且我为每个参数制作了一个输入组件。
[dcc.Input(type = 'number', id = 'input %i'%i) for i in range(20)]
Run Code Online (Sandbox Code Playgroud)
我想要一个按钮html.Button('populate parameters', id = 'button populate')
,它应该为所有输入填充最佳预装值。
代码应如下所示,但它不起作用。
for i in range(20):
@app.callback(
dash.dependencies.Output('input %i'%i, 'value'),
[dash.dependencies.Input('button populate', 'n_clicks')]
)
def update(ignore):
return np.random.uniform()
Run Code Online (Sandbox Code Playgroud)
我是否必须为每个具有相同功能的输出编写 20 个回调?我找不到一次性制作它们的方法(循环?)
Sho*_*alt 13
我已经处理过同样的问题并找到了解决方案。你所做的是绕过装饰器并app.callback
直接调用函数:
def update(ignore):
return np.random.uniform()
for i in range(20):
app.callback(
dash.dependencies.Output('input %i' % i, 'value'),
[dash.dependencies.Input('button populate', 'n_clicks')]
)(update)
Run Code Online (Sandbox Code Playgroud)
在dash >= 1.11.0中,您可以使用模式匹配回调。定义回调时不需要循环。
dash.dependecies.ALL
:from dash.dependencies import Input, Output, State, ALL
Run Code Online (Sandbox Code Playgroud)
MATCH
和ALLSMALLER
。id
id
使用字典定义您的组件。您可以选择任何键,但例如type
和id
是相当合理的选择。所以,而不是[dcc.Input(type = 'number', id = 'input %i'%i) for i in range(20)]
Run Code Online (Sandbox Code Playgroud)
使用
[
dcc.Input(type='number',
id={
'type': 'my-input-type',
'id': 'input %i' % i
}) for i in range(20)
]
Run Code Online (Sandbox Code Playgroud)
@app.callback
ALL
定义回调时使用回调选择器:@app.callback(
dash.dependencies.Output({
'type': 'my-input-type',
'id': ALL
}, 'value'), [dash.dependencies.Input('button populate', 'n_clicks')])
def update(ignore):
return np.random.uniform()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7120 次 |
最近记录: |