import streamlit as st
# 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"]
}
# Streamlit app
st.title("Country and City Picker")
# Initialize session state for country and city
if "selected_country" not in st.session_state:
st.session_state.selected_country = None
if "selected_city" not in st.session_state:
st.session_state.selected_city = None
# Function to reset city when country changes
def on_country_change():
st.session_state.selected_city = None
# Country selection
selected_country = st.selectbox(
"Select a country:",
options=[""] + list(country_city_data.keys()),
index=0 if st.session_state.selected_country is None else list(country_city_data.keys()).index(st.session_state.selected_country) + 1,
on_change=on_country_change,
key="selected_country"
)
# City selection
if selected_country:
city_index = 0 if st.session_state.selected_city is None else country_city_data[selected_country].index(st.session_state.selected_city) + 1
city_options = [""] + country_city_data[selected_country]
def set_city():
# no idea why this is needed, why can't we use key="selected_city" below
st.session_state.selected_city = st.session_state.selected_city_change
selected_city = st.selectbox(
"Select a city:",
options=city_options,
index=city_index,
key="selected_city_change",
on_change=set_city,
)
st.write(f"Selected Country: {selected_country}")
if selected_city:
st.write(f"Selected City: {selected_city}")
def reset_selection():
st.session_state.selected_country = None
st.session_state.selected_city = None
st.button("Reset", on_click=lambda: reset_selection())