如何清除 PySimpleGUI 中绘制的图形?

How to clear the graph drawn inPySimpleGUI?

有没有办法在重新绘制新图像之前清除 PySimpleGUI 中的图形?我注意到函数 window["-GRAPH-"].draw_image() 在程序 运行 一段时间内导致严重的内存泄漏, 因为它试图将图片堆叠在所有绘制的图像之上。

背景:

My app is trying to show a live feed from a webcam, meanwhile will also do some drawing (depending on mouse click) on top of the camera feed. In order to detect the mouse click event from the camera feed, im using sg.Graph to capture mouse position.

sample_app_display: user label the box of object in a live camera feed

代码片段:

sg.Graph(853, (0, 480), (853, 0), key="-GRAPH-", change_submits=True, drag_submits=False)

...

camera = my_opencv_library(device=0)
while True:
    event, values = window.read(timeout=20)
    if event == "-GRAPH-":
        camera.update_coordinate(values["-GRAPH-"])

    # obtain live feed with runtime drawing (based on mouse click)
    frame = camera.get_frame()
    imgbytes = cv2.imencode(".png", frame)[1].tobytes()
    window["-GRAPH-"].draw_image(data=imgbytes, location=(0,0))

Erase the Graph - Removes all figures previously "drawn" using the Graph methods

通过

擦除sg.Graph上的所有数字
window['-GRAPH-'].erase()

Remove from the Graph the figure represented by id.

通过ids

擦除sg.Graph上的指定图形
window['-GRAPH-'].delete_figure(ids)

只要你调用绘图基元,ids就会给你,比如

ids = window["-GRAPH-"].draw_image(data=imgbytes, location=(0,0))

更新代码

sg.Graph(853, (0, 480), (853, 0), key="-GRAPH-", change_submits=True, drag_submits=False)

...

camera = my_opencv_library(device=0)
ids = None
while True:
    event, values = window.read(timeout=20)
    if event == "-GRAPH-":
        camera.update_coordinate(values["-GRAPH-"])

    # obtain live feed with runtime drawing (based on mouse click)
    frame = camera.get_frame()
    imgbytes = cv2.imencode(".png", frame)[1].tobytes()
    if ids is not None:
       window["-GRAPH-"].delete_figure(ids)
    ids = window["-GRAPH-"].draw_image(data=imgbytes, location=(0,0))