0

I add some spheres to my Pyvista plot and try to make them pickable:

for index, center in enumerate(centers):
    sphere = pv.Sphere(radius=radius, center=center)
    plotter.add_mesh(sphere, color=thisColor, pickable=True)
    plotter.enable_cell_picking(mesh=sphere, callback=makePickCallback(index), show=True, show_message=True, through=False)

I assume that each sphere would get an individual callback, constructed using the following function:

def makePickCallback(index):
    indexCopy = deepcopy(index)
    return lambda p: print(str(indexCopy) + " " + str(p))

But it seems that all spheres, and every other element in the plot just calls the callback that was constructed in the last iteration of the for loop.

Now I wonder - how can I install a different picking callback for each mesh in the scene? Or how can I identify which mesh was clicked?

Michael
  • 7,407
  • 8
  • 41
  • 84
  • I'm pretty sure this is a duplicate of [this](https://stackoverflow.com/questions/3431676/creating-functions-in-a-loop), but I don't yet see how. `index` is an int by the way, so copying is unnecessary (ints are immutable). As far as I can tell `makePickCallback(index)` creates a new lambda with no closure variables, so you should be avoiding the issue. Can you post a simple but complete code snippet that reproduces the problem? I want to make sure there's nothing lost "in translation". – Andras Deak -- Слава Україні Oct 13 '21 at 17:18
  • OK, no, it seems this is pyvista's doing. From the docs of `enable_cell_picking()`: "_When `through` is `False`, all meshes in the scene are available for picking and this argument is ignored. If you would like to only pick a single mesh in the scene, use the `pickable=False` argument when adding the other meshes to the scene_". This sounds like you can only set a single callback at a time, and that one callback should figure out which mesh is being picked (unless that's readily done by the callback mechanism). In other words there should probably be a single call to `enable_cell_picking()`. – Andras Deak -- Слава Україні Oct 13 '21 at 17:22
  • (I'm just leaving comments for now because I'm not sure at all, only guessing.) – Andras Deak -- Слава Україні Oct 13 '21 at 17:37

0 Answers0