Fix memory leak due to Images of Graph (PySimpleGui27)

- Graph used a list self.Images to which new images where appended on
   DrawImage.  Neither in DeleteFigure nor in Erase were any elements
   removed from that list.  Thus any added image was kept in memory as
   long as the corresponding Graph was; even if it wasn't used
   anymore.

 - Even though self.Images is not referred to in any other way,
   removing the list completely does not work; the result
   is that no images are drawn on the Graph.

 - The implemented solution uses a dictionary (id -> image) to keep
   only used images in self.Images.
This commit is contained in:
Daniel Jour 2019-05-13 22:51:23 +02:00
parent bdaf9503ee
commit 78c84b9f8f

View file

@ -2031,7 +2031,7 @@ class Graph(Element):
self.DragSubmits = drag_submits self.DragSubmits = drag_submits
self.ClickPosition = (None, None) self.ClickPosition = (None, None)
self.MouseButtonDown = False self.MouseButtonDown = False
self.Images = [] self.Images = {}
self.RightClickMenu = right_click_menu self.RightClickMenu = right_click_menu
super().__init__(ELEM_TYPE_GRAPH, background_color=background_color, size=canvas_size, pad=pad, key=key, super().__init__(ELEM_TYPE_GRAPH, background_color=background_color, size=canvas_size, pad=pad, key=key,
@ -2186,9 +2186,9 @@ class Graph(Element):
print('*** WARNING - The Graph element has not been finalized and cannot be drawn upon ***') print('*** WARNING - The Graph element has not been finalized and cannot be drawn upon ***')
print('Call Window.Finalize() prior to this operation') print('Call Window.Finalize() prior to this operation')
return None return None
self.Images.append(image)
try: # in case closed with X try: # in case closed with X
id = self._TKCanvas2.create_image(converted_point, image=image, anchor=tk.NW) id = self._TKCanvas2.create_image(converted_point, image=image, anchor=tk.NW)
self.Images[id] = image
except: except:
id = None id = None
return id return id
@ -2200,6 +2200,7 @@ class Graph(Element):
print('*** WARNING - The Graph element has not been finalized and cannot be drawn upon ***') print('*** WARNING - The Graph element has not been finalized and cannot be drawn upon ***')
print('Call Window.Finalize() prior to this operation') print('Call Window.Finalize() prior to this operation')
return None return None
self.Images = {}
try: # in case window was closed with X try: # in case window was closed with X
self._TKCanvas2.delete('all') self._TKCanvas2.delete('all')
except: except:
@ -2208,6 +2209,7 @@ class Graph(Element):
def DeleteFigure(self, id): def DeleteFigure(self, id):
try: try:
del self.Images[id]
self._TKCanvas2.delete(id) self._TKCanvas2.delete(id)
except: except:
print('DeleteFigure - bad ID {}'.format(id)) print('DeleteFigure - bad ID {}'.format(id))