Need help with deleting only one DrawImage on my canvas in PySimpleGUI. Canvas is loaded with a background image (100% of the canvas), and has 5 other DrawImage items on it (various sizes). When I click on one of those 5 images, I want THAT to be gone (deleted), but the background image to stay.
Using get_figures_at_location with coordinates derived from mouse click to delete the one image I want to go away. But my routine also deletes the background.
Any ideas? Could not find a way to do it after searching numerous forums.
Save the id returned when you draw background image by using draw_image
, delete it after you confirmed it is not the background image by the 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
Following code show to delete all figures after mouse clicked on the figures. (Remember to replace it with your background image)
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()