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

如何在固定背景图上叠加绘制圆形并仅更新删除圆形不修改背景

解决方案

核心原理

PySimpleGUI的Graph控件所有绘制接口都会返回唯一的图形ID,也支持给同类图形打标签,你可以通过ID或标签精准删除圆形,完全不会影响提前绘制的背景图。

方案1:标签法(PySimpleGUI 4.60+ 推荐,代码最简洁)

所有圆形绘制时统一打相同标签,删除时直接按标签批量删除即可:

import PySimpleGUI as sg
from PIL import Image

layout = [sg.Graph(canvas_size=(1065, 460), graph_bottom_left=(0, 0), 
graph_top_right=(1065, 460), key="-GRAPH-")]
window = sg.Window("Demo", layout, finalize=True)
graph = window["-GRAPH-"]

# 第一步:先绘制背景图(坐标适配:Graph原点在左下角,所以图片左上角放在(0,460)刚好铺满画布)
graph.DrawImage(filename='C:/background.png', location=(0, 460))

def circle_position(x,y,r):
    # 绘制圆形时统一加tag标记
    graph.DrawCircle((x,y), r, line_color='red', tag='circle')

# 事件处理部分
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
    elif (event =="Display Error Code") or (event == 'Submit'):
        # 直接删除所有带circle标签的图形,不会碰背景
        graph.DeleteFiguresWithTag('circle')
        circle_position(324,257,16)
    if (values[0] == "1002") :  # 第二个圆形
        graph.DeleteFiguresWithTag('circle')
        circle_position(342,303,16)
window.close()

方案2:ID列表法(兼容所有版本)

如果你的PySimpleGUI版本不支持标签功能,维护一个列表存所有圆形的ID,删除时遍历删除即可:

import PySimpleGUI as sg
from PIL import Image

layout = [sg.Graph(canvas_size=(1065, 460), graph_bottom_left=(0, 0), 
graph_top_right=(1065, 460), key="-GRAPH-")]
window = sg.Window("Demo", layout, finalize=True)
graph = window["-GRAPH-"]
# 存储所有圆形的ID
circle_ids = []

# 绘制背景
graph.DrawImage(filename='C:/background.png', location=(0, 460))

def circle_position(x,y,r):
    cid = graph.DrawCircle((x,y), r, line_color='red')
    circle_ids.append(cid)

def erase_all_circles():
    # 遍历删除所有圆形
    for cid in circle_ids:
        graph.DeleteFigure(cid)
    # 清空列表准备存下一批圆形ID
    circle_ids.clear()

# 事件处理部分
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
    elif (event =="Display Error Code") or (event == 'Submit'):
        erase_all_circles()
        circle_position(324,257,16)
    if (values[0] == "1002") :  # 第二个圆形
        erase_all_circles()
        circle_position(342,303,16)
window.close()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:15:03