Py.Cafe

maartenbreddels/

country-city-selector-streamlit

Country and City Picker

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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())