如何在Options来自回调时动态设置DCC.Dropdown中的默认值? [英] How to dynamically set a default value in a dcc.Dropdown when options come from a callback?

查看:83
本文介绍了如何在Options来自回调时动态设置DCC.Dropdown中的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是 Dash 应用程序代码 (app.py) 的最小示例:

Here is a minimal example of a Dash app code (app.py):

# Libraries
import csv
import pandas as pd
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output, State

# CSV files generation

row_list = [
    ["SN", "Name", "Quotes"],
    [1, "Buddha", "What we think we become"],
    [2, "Mark Twain", "Never regret anything that made you smile"],
    [3, "Oscar Wilde", "Be yourself everyone else is already taken"]
]
with open('quotes.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=',')
    writer.writerows(row_list)
    
    
import csv
with open('innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["SN", "Name", "Contribution"])
    writer.writerow([1, "Linus Torvalds", "Linux Kernel"])
    writer.writerow([2, "Tim Berners-Lee", "World Wide Web"])
    writer.writerow([3, "Guido van Rossum", "Python Programming"])


# Style
external_stylesheets = ['assets/style.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)


# Layout
app.layout = html.Div([
    html.Div([  
        dcc.Dropdown(
            id='dropdown_div',
            options=[
                {'label': 'Quotes', 'value': 'quotes.csv'},
                {'label': 'Innovators', 'value': 'innovators.csv'}
            ],
            value='quotes.csv'   
        )
    ]),
    html.Div([
       dcc.Dropdown(
            id='count_div'
       )
    ])
])

# Callback function
@app.callback(
    dash.dependencies.Output('count_div', 'options'),
    [dash.dependencies.Input('dropdown_div', 'value')])
def loadfile(path):
    df = pd.read_csv(path) 
    return [{'label': i, 'value': i} for i in df['Name'].drop_duplicates()]

# Main
if __name__ == '__main__':
    app.run_server(debug=True)

我需要将第二个 Dropdown 的第一个值动态设置为其默认值.

I need the first value of the second Dropdown to be dynamically set as its default value.

在这个例子中,第二个下拉菜单将显示

In this example, the second dropdown would show

  • 当 Quotes 为第一个下拉列表的选定值时,默认值为 Buddha.
  • 当 Innovators 是第一个下拉列表的选定值时,Linus Torvalds 作为默认值.

推荐答案

解决方案是

  • 向回调函数添加一个输出,将默认值发送到第二个 ddc.Dropdown
  • 添加默认值到return
# Callback function
@app.callback(
    [dash.dependencies.Output('count_div', 'options'),
    dash.dependencies.Output('count_div', 'value')],
    [dash.dependencies.Input('dropdown_div', 'value')])
def loadfile(path):
    df = pd.read_csv(path) 
    return [{'label': i, 'value': i} for i in df['Name'].drop_duplicates()], df['Name'].drop_duplicates()[0]

这篇关于如何在Options来自回调时动态设置DCC.Dropdown中的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆