import dash
from dash import dcc, html
from dash.dependencies import Input, Output, State
# Sample data for countries and cities
country_city_data = {
"USA": ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"],
"Canada": ["Toronto", "Vancouver", "Montreal", "Calgary", "Ottawa"],
"Australia": ["Sydney", "Melbourne", "Brisbane", "Perth", "Adelaide"],
"India": ["Mumbai", "Delhi", "Bangalore", "Hyderabad", "Chennai"],
"UK": ["London", "Manchester", "Birmingham", "Leeds", "Glasgow"]
}
# Initialize the Dash app
app = dash.Dash(__name__)
# Layout of the app
app.layout = html.Div([
html.H1("Country and City Picker"),
dcc.Dropdown(
id='country-dropdown',
options=[{'label': country, 'value': country} for country in country_city_data.keys()],
placeholder="Select a country",
value=''
),
dcc.Dropdown(
id='city-dropdown',
options=[],
placeholder="Select a city",
value=''
),
html.Div(id='output-div'),
html.Button('Reset', id='reset-button', n_clicks=0),
])
# Callback to update city dropdown based on selected country
@app.callback(
Output('city-dropdown', 'options', allow_duplicate=True),
Output('city-dropdown', 'value', allow_duplicate=True),
Input('country-dropdown', 'value'),
prevent_initial_call=True
)
def update_city_dropdown(selected_country):
print("update_city_dropdown")
if selected_country:
cities = [{'label': city, 'value': city} for city in country_city_data[selected_country]]
return cities, ''
return [], ''
# Callback to display selected country and city
@app.callback(
Output('output-div', 'children'),
Input('country-dropdown', 'value'),
Input('city-dropdown', 'value')
)
def display_selected_values(selected_country, selected_city):
print("display_selected_values")
if selected_country and selected_city:
return [html.P(f"Selected Country: {selected_country}"), html.P(f"Selected City: {selected_city}")]
return []
# Callback to reset the dropdowns
@app.callback(
Output('country-dropdown', 'value', allow_duplicate=True),
Output('city-dropdown', 'options', allow_duplicate=True),
Output('city-dropdown', 'value', allow_duplicate=True),
Input('reset-button', 'n_clicks'),
prevent_initial_call=True
)
def reset_dropdowns(n_clicks):
print("Button")
if n_clicks > 0:
return '', [], ''
return dash.no_update, dash.no_update, dash.no_update
# Run the app
if __name__ == '__main__':
app.run_server(debug=True)