[Python] how can I get the name of svg element when i click on it in nicegui

Discussão em 'Python' iniciado por Stack, Abril 16, 2025.

  1. Stack

    Stack Membro Participativo

    I have a NiceGUI page with an SVG image consisting of two elements (a circle and a square). I need to check which element of this image was clicked when the SVG image is clicked, so that I can handle it.

    I want the event "circle clicked" to be triggered when the circle is clicked, and the event "square clicked" to be triggered when the square is clicked. I am trying to implement this through a handler, but I don't know what to write in the handler function. I am attaching the code.

    My method 1:

    from nicegui import ui

    def my_handler(event_args):
    print("Button clicked!")

    with ui.row():
    svg_element = ui.html('''
    <svg width="200" height="200" style="border: 1px solid black;">
    <circle cx="50" cy="50" r="40" fill="red" class="clickable-circle"/>
    <rect x="100" y="10" width="80" height="80" fill="blue" class="clickable-square"/>
    </svg>
    ''')

    svg_element.on('click', js_handler='(click) => { console.log(event.target.clickable-circle); }')

    ui.run(port = 8082)


    My method 2:

    from nicegui import ui


    def my_handler(event_args):
    element = event_args.sender
    # ???????


    with ui.row():
    svg_element = ui.html('''
    <svg width="200" height="200" style="border: 1px solid black;">
    <circle cx="50" cy="50" r="40" fill="red" class="clickable-circle"/>
    <rect x="100" y="10" width="80" height="80" fill="blue" class="clickable-square"/>
    </svg>
    ''')

    svg_element.on('click', handler=my_handler)

    ui.run(port=8082)


    Thank you all for your help.

    Continue reading...

Compartilhe esta Página