简体   繁体   English

使用 ipywidgets 下拉 function 返回不同的输出

[英]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.我正在尝试使用 ipywidgets 的下拉菜单来返回不同城市的纬度和经度。 I'm tyring to implement the ideas from this forum, ipywidgets dropdown widgets: what is the onchange event?我很想实现这个论坛的想法, ipywidgets 下拉小部件:什么是 onchange 事件? , but since I'm relatively new to python, I might need a bit of direction. ,但由于我对 python 比较陌生,我可能需要一些指导。 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将坐标放在字典locations
  2. change["new"] will get the new option value of a city change["new"]将获得一个城市的新选项值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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