[英]ipyleaflet on_click event in for loop calls function on each iteration
I've been plotting markers on a map, each with its own location and sample id.我一直在 map 上绘制标记,每个标记都有自己的位置和样本 ID。 I'm trying to add a click_event on each marker so that each marker will print out its sample Id upon being clicked.
我正在尝试在每个标记上添加一个 click_event,以便每个标记在被单击时打印出其样本 ID。 My main issue is with the on_click event, which seems to call the button_click function with each iteration before I even get to click the marker.
我的主要问题是 on_click 事件,它似乎在我点击标记之前每次迭代都会调用 button_click function。
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
One strange thing I noticed was that if I set the on_click event to call a function without a parameter (simple "hello world" function in this case), it worked with no problems however, I need a parameter from within the for loop,我注意到的一件奇怪的事情是,如果我将 on_click 事件设置为调用没有参数的 function(在这种情况下为简单的“hello world”function),它可以正常工作,但是,我需要来自 for 循环中的参数,
One possible solution is to create a function that returns the appropriate function:一种可能的解决方案是创建一个返回适当 function 的 function:
def create_button_click(val):
def button_click():
print(val)
return button_click
Then you can pass this returned function to the marker on_click event:然后您可以将此返回的 function 传递给标记 on_click 事件:
new_marker.on_click(create_button_click(val))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.