gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:39:07 24 4
gpt4 key购买 nike

我一直在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com