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

NiceGUI交互式图片:如何仅刷新source同时保留content

解决NiceGUI interactive_image更新直播流时保留SVG标注的问题

问题核心在于interactive_image.set_source()方法会触发元素整体重渲染,导致绑定的SVG content被重置。可以通过直接操作底层DOM元素更新图片源,避免重置content:

  • 替换ii.set_source()为JavaScript直接修改img标签的src属性,仅更新视频流,不影响叠加的SVG内容
  • 保留原有的content绑定和点击事件逻辑

修改后的代码如下:

import time
from nicegui import ui, MouseEventArguments

class SVGContent:
    def __init__(self):
        self.content = ''
        self.color = 'red'  # 补充原代码中未定义的color变量

svgContent = SVGContent()

def mouse_handler(e: MouseEventArguments):
    if e.type == 'click':
        svgContent.content += f'<circle cx="{e.image_x}" cy="{e.image_y}" r="15" fill="none" stroke="{svgContent.color}" stroke-width="4" />'

ii = ui.interactive_image(
    on_mouse=mouse_handler, 
    events=['click', 'mousedown', 'mouseup'], 
    cross=True
)

# 通过JavaScript直接更新img的src,避免重置content
ui.timer(interval=0.1, callback=lambda: ii.element.run_javascript(
    f'element.querySelector("img").src = "http://localhost:3000/video/stream1?{time.time()}"'
))

ii.bind_content_from(svgContent, 'content')

ui.run()

关键说明:

  • ii.element.run_javascript()直接操作interactive_image的DOM元素,定位内部img标签更新src,不会触发整个元素重渲染
  • 原有的content绑定逻辑保持生效,鼠标点击生成的SVG标注会持续保留,不受视频流更新影响
  • 补充了原代码中缺失的color变量,确保生成的标注圆有正确的描边颜色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 17:42:10