DrawImage 删除 - PySimpleGUI

DrawImage delete - PySimpleGUI

需要帮助在 PySimpleGUI 中删除我 canvas 上的一个 DrawImage。 Canvas 加载了背景图像(canvas 的 100%),并且上面有 5 个其他 DrawImage 项目(各种尺寸)。当我点击这 5 张图片中的一张时,我希望它消失(删除),但背景图片保留。

使用get_figures_at_location和鼠标点击得到的坐标来删除我想离开的一张图片。但是我的例程也删除了背景。

有什么想法吗?找了很多论坛都找不到方法。

保存使用draw_image绘制背景图时返回的id,确认不是id绘制的背景图后删除

draw = window['-GRAPH-']
bg_id = draw.draw_image(filename=filename)

...

figures = draw.get_figures_at_location((x, y))
if figures and figures[0] != bg_id:
    draw.delete_figure(figures[-1])    # index -1 for last one or top one

以下代码显示鼠标点击图形后删除所有图形。 (记得用你的背景图片替换它)

from io import BytesIO
from random import randint
from PIL import Image
import PySimpleGUI as sg

def image_to_data(im):
    """
    Image object to bytes object.
    : Parameters
      im - Image object
    : Return
      bytes object.
    """
    with BytesIO() as output:
        im.save(output, format="PNG")
        data = output.getvalue()
    return data

width, height = size = (640, 480)

im = Image.open("D:/desktop.png")
new_im = im.resize(size)

font = ("Courier New", 11)
sg.theme("DarkBlue3")
sg.set_options(font=font)

layout = [
    [sg.Button('Redraw')],
    [sg.Graph(size, (0, 0), size, enable_events=True, key='-GRAPH-')],
]
window = sg.Window('Title', layout, finalize=True)
draw = window['-GRAPH-']

background = draw.draw_image(data=image_to_data(new_im), location=(0, height))
ids = [draw.draw_image(data=emoji, location=(randint(0, width), randint(0, height)))
    for emoji in sg.EMOJI_BASE64_HAPPY_LIST]
print(ids)
while True:

    event, values = window.read()

    if event in (sg.WINDOW_CLOSED, 'Exit'):
        break
    elif event == '-GRAPH-':
        location = values[event]
        figures = draw.get_figures_at_location(location)
        for figure in figures:
            if figure != background:
                draw.delete_figure(figure)
                ids.remove(figure)
    elif event == 'Redraw':
        for figure in ids:
            draw.delete_figure(figure)
        ids = [draw.draw_image(data=emoji, location=(randint(0, width), randint(0, height)))
            for emoji in sg.EMOJI_BASE64_HAPPY_LIST]

window.close()