简体   繁体   中英

Using ipywidgets drop-down function to return different outputs

I'm trying to use a drop-down menu from ipywidgets to return latitudes and longitudes for different cities. I'm tyring to implement the ideas from this forum, ipywidgets dropdown widgets: what is the onchange event? , but since I'm relatively new to python, I might need a bit of direction. This is what I have so far:

import ipyleaflet
import ipywidgets as widgets

w = widgets.Dropdown(
    options=['Sydney', 'Canberra', 'Brisbane', 'Adelaide'],
    value='Sydney',
    description='Location:',
)
lat = -35
lon = 150
def on_change(change):
    if change['type'] == 'change' and change['name'] == 'value':
        print("latitude %s, " % lat)
        print("longtitude %s, " % lon)

w.observe(on_change)

display(w)

At the moment, each city is returning the lat and lon for Canberra since these are the coordinates I've actually provided. But I'm not sure how to adjust the code so that coordinates for each city are associated with the city in the drop-down menu. Any help would be greatly appreciated.

import ipyleaflet
import ipywidgets as widgets

w = widgets.Dropdown(
    options=['Sydney', 'Canberra', 'Brisbane', 'Adelaide'],
    value='Sydney',
    description='Location:',
)

locations = {
    "Sydney": {"lat": -30, "lon": 150},
    "Canberra": {"lat": 30, "lon": 120},
    "Brisbane": {"lat": 20, "lon": 80},
    "Adelaide": {"lat": -150, "lon": 30},
}


def on_change(change):
    if change['type'] == 'change' and change['name'] == 'value':
        new_loc = locations[change["new"]]
        print("latitude %s, " % new_loc["lat"])
        print("longtitude %s, " % new_loc["lon"])

w.observe(on_change)

display(w)
  1. Put coordinates in the dict locations
  2. change["new"] will get the new option value of a city

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM