[Python] How to accurately pick/select cells in PyVista with single mouse click?

Discussão em 'Python' iniciado por Stack, Junho 30, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to implement single-click cell selection in PyVista to get the correct cell index when clicking on a mesh.

    I've tried using pv.Plotter().enable_cell_picking() but this has two issues: the first is that it seems to allow only rectangle selection and the callback is not returning a single cell, but an UnstructuredGrid object from which I can't extract the cell index.

    I've also tried with enable_element_picking which allows for a single cell selection, but still return an UnstructuredGrid object.

    Here is a simple example to reproduce the problem

    import pyvista as pv
    import numpy as np

    pl = pv.Plotter()
    mesh = pv.Sphere()
    mesh.cell_data['colors'] = np.ones(mesh.n_cells) * 0
    pl.add_mesh(mesh, show_edges=True, scalars='colors',)

    def my_callback(picked_cell):
    """
    Callback function to print the cell index.
    This function is triggered when a cell is picked.
    """
    cell_index = picked_cell.index
    mesh.cell_data['colors'][:] = 0
    mesh.cell_data['colors'][cell_index] = 1

    pl.update()
    print(f"You clicked on cell index: {cell_index}")

    pl.enable_element_picking(
    callback=my_callback,
    mode='cell',
    picker='cell',
    )
    pl.show()

    Continue reading...

Compartilhe esta Página