如何更新 RadioItems 选项?

How to update RadioItems options?

如何在选择其他 RadioItem 选项时更新一个 RadioItem 选项?

更多详情:

我这样试过,还是不行:

import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)


app.layout = html.Div([

    html.Div([
        html.Div(children=[
            html.H1(children="main-groups")
        ]),
        dcc.RadioItems(
            id="radio1",
            options=[
                {'label': 'New York City', 'value': 'NYC'},
                {'label': 'Montréal', 'value': 'MTL'},
                {'label': 'San Francisco', 'value': 'SF'}
            ],
        )]),

    html.Div([
        html.Div(children=[
            html.H1(children="sub-groups")
        ]),
        dcc.RadioItems(
                id="radio2",
                options=[
                ],
        ),
        html.Div(children=[
            html.H1(id="res", children="results")
        ]),
        ])


])


@app.callback(
              [Output('radio2', 'options')],
              [Input('radio1', 'value')])

def chnage_selection(val):
    print("change main radio: {}".format(val))

    if val == "NYC":
        return [
                    {'label': 'a1', 'value': 'a1'},
                    {'label': 's1', 'value': 's1'}
                ]
    elif val == "MTL":
        return [
                    {'label': 'a2', 'value': 'a2'},
                    {'label': 's2', 'value': 's2'}
                ]
    else:
        return [
                    {'label': 'a3', 'value': 'a3'},
                    {'label': 's3', 'value': 's3'}
                ]

    print("Error")
    return None



def main():
    app.run_server(debug=True)

if __name__ == "__main__":
    main()

不要用列表包围你的单一 Output 或用列表包围你的 return 价值观。

所以你可以改变你的回调:

@app.callback([Output("radio2", "options")], [Input("radio1", "value")])
def chnage_selection(val):
    print("change main radio: {}".format(val))

    if val == "NYC":
        return [{"label": "a1", "value": "a1"}, {"label": "s1", "value": "s1"}]
    elif val == "MTL":
        return [{"label": "a2", "value": "a2"}, {"label": "s2", "value": "s2"}]
    else:
        return [{"label": "a3", "value": "a3"}, {"label": "s3", "value": "s3"}]

    print("Error")
    return None

对此:

@app.callback(Output("radio2", "options"), [Input("radio1", "value")])
def chnage_selection(val):
    print("change main radio: {}".format(val))

    if val == "NYC":
        return [{"label": "a1", "value": "a1"}, {"label": "s1", "value": "s1"}]
    elif val == "MTL":
        return [{"label": "a2", "value": "a2"}, {"label": "s2", "value": "s2"}]
    else:
        return [{"label": "a3", "value": "a3"}, {"label": "s3", "value": "s3"}]

    print("Error")
    return None

添加更多关于您的原始代码发生了什么的解释。原始回调的预期 return 值是一个包含单个元素的列表。因此,当您 return 在检查中编辑选项列表时,它会将每个选项对象视为单独的回调输出。