python - for循环中的ipyleaflet on_click事件在每次迭代时调用函数

标签 python python-3.x ipyleaflet

我一直在 map 上绘制标记,每个标记都有自己的位置和样本 ID。我正在尝试在每个标记上添加一个 click_event,以便每个标记在被单击时打印出其样本 ID。我的主要问题是 on_click 事件,在我点击标记之前,它似乎在每次迭代时调用了 button_click 函数。

capitol_loc = (38.89, -77.02) #(lat, long)
m = Map(center=(capitol_loc), zoom=14)
locations = [(38.89, -77.02), (38.88, -77.02), (38.88, -77.01), (38.873, -77.02), (38.891, -77.02), (38.89, -77.022)]

def button_click(sample_id):
    print(str(sample_id))


for i in range(len(locations)):
    new_marker_loc = (locations[i][0], locations[i][1])
    new_marker = Marker(location=new_marker_loc, draggable=False)
    
    sample_id = "Sample Id: 1234567"
    
    new_marker.on_click(button_click(sample_id)) 
    m.add_layer(new_marker)
    
m  #Display map

输出:enter image description here

我注意到的一件奇怪的事情是,如果我将 on_click 事件设置为调用一个不带参数的函数(在本例中为简单的“hello world”函数),它可以正常工作,但是,我需要 for 中的一个参数循环,

最佳答案

一个可能的解决方案是创建一个返回适当函数的函数:

def create_button_click(val):
    def button_click():
        print(val)
    
    return button_click

然后你可以将这个返回函数传递给标记的on_click事件:

new_marker.on_click(create_button_click(val))

关于python - for循环中的ipyleaflet on_click事件在每次迭代时调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66360839/

相关文章:

python-3.x - 您知道如何在 Databricks 集群上安装 'ODBC Driver 17 for SQL Server' 吗?

python3 mariadb ssl : The requested data were not available

python-3.x - 按列位置分组的 Pandas 数据框

python - 如何通过 OpenStreetMap (Python) 绘制数据

python - 为我的 Django 项目中的每个应用程序创建自定义 404 错误?

python - (python) matplotlib pyplot show() .. 阻塞与否?

python - 安装时 ipyleaflet map 未在 jupyter 笔记本中渲染

python - 将闭包从 Cython 传递到 C++

python - 将列表中的项目映射到列表列表