You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NiceGUI中点击SVG元素时获取其名称并触发对应事件

解决NiceGUI中SVG元素点击区分的问题

要实现点击SVG内的圆形和方形触发不同事件,关键是在点击时把目标元素的标识传递给Python处理函数。以下是可行的解决方案:

完整实现代码

from nicegui import ui

def handle_svg_click(event_args):
    # 从事件参数中获取前端传来的元素标识
    element_class = event_args.args['element_class']
    if element_class == 'clickable-circle':
        print('circle clicked')
    elif element_class == 'clickable-square':
        print('square 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>
    ''')
    # 通过JS handler获取点击目标的类名,并传递给Python处理函数
    svg_element.on('click', js_handler='(event) => { return {element_class: event.target.classList[0]} }', handler=handle_svg_click)

ui.run(port=8082)

代码说明

  1. JS Handler部分:

    • 利用event.target获取实际被点击的SVG子元素(circle或rect)
    • 通过event.target.classList[0]获取元素的类名(你定义的clickable-circle/clickable-square)
    • 将类名作为参数返回,NiceGUI会自动把这个参数传递给Python的处理函数
  2. Python处理函数:

    • 通过event_args.args['element_class']获取前端传来的类名
    • 根据类名判断点击的元素,执行对应逻辑

其他可选方案:通过标签名判断

如果你不想用类名,也可以通过元素的标签名(circle/rect)来区分:

from nicegui import ui

def handle_svg_click(event_args):
    element_tag = event_args.args['element_tag']
    if element_tag == 'circle':
        print('circle clicked')
    elif element_tag == 'rect':
        print('square 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"/>
            <rect x="100" y="10" width="80" height="80" fill="blue"/>
        </svg>
    ''')
    svg_element.on('click', js_handler='(event) => { return {element_tag: event.target.tagName.toLowerCase()} }', handler=handle_svg_click)

ui.run(port=8082)

对你原有代码的问题分析

  • 方法1:JS handler的写法错误,console.log(event.target.clickable-circle)是无效语法,而且没有将数据传递给Python函数,无法触发后端的区分逻辑。
  • 方法2:event_args.sender指向的是整个ui.html元素(即SVG容器),不是被点击的子元素,所以无法直接通过它判断点击的是圆形还是方形,必须通过JS传递子元素的信息。

内容的提问来源于stack exchange,提问作者CameL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 09:48:13