From b04472619b205cee919de8451acf25d26b40392a Mon Sep 17 00:00:00 2001 From: Simon Forman Date: Tue, 16 Apr 2024 12:21:00 -0700 Subject: [PATCH] Cache x y to deal with resizing canvas. --- reticule.py | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/reticule.py b/reticule.py index fa8c424..9c963c0 100644 --- a/reticule.py +++ b/reticule.py @@ -29,6 +29,12 @@ class Reticule: self.color = color self.item_ids = [] self.init_reticule() + self.xy_cache = 0, 0 + self.canvas.bind( + '', + self.handle_canvas_resize, + add='+', + ) def get_reticule_coords(self, x, y): ''' @@ -36,11 +42,14 @@ class Reticule: rectangle yield coords for four lines and an oval suitable for passing to canvas.coords() method. ''' - width, height = int(self.canvas['width']), int(self.canvas['height']) + width = int(self.canvas['width']) + height = int(self.canvas['height']) + top = y - self.radius_y left = x - self.radius_x bottom = y + self.radius_y right = x + self.radius_x + yield 0, y, left, y yield right, y, width - 1, y yield x, 0, x, top @@ -51,6 +60,7 @@ class Reticule: append = self.item_ids.append w, h = int(self.canvas['width']), int(self.canvas['height']) coords = self.get_reticule_coords(w >> 1, h >> 1) # Center. + append(canvas.create_line(*next(coords), fill=self.color)) append(canvas.create_line(*next(coords), fill=self.color)) append(canvas.create_line(*next(coords), fill=self.color)) @@ -58,6 +68,7 @@ class Reticule: append(canvas.create_oval(*next(coords), outline=self.color)) def set_reticule(self, x, y): + self.xy_cache = x, y coords = self.get_reticule_coords(x, y) for item_id, item_coords in zip(self.item_ids, coords): self.canvas.coords(item_id, *item_coords) @@ -65,6 +76,12 @@ class Reticule: def handle_set_event(self, event): self.set_reticule(event.x, event.y) + def handle_canvas_resize(self, _event): + # We're going to assume that some other callback has updated the + # canvas values. Otherwise we could get the new width and height + # from the Configure event. + self.set_reticule(*self.xy_cache) + if __name__ == '__main__': from tkinter import * @@ -77,7 +94,6 @@ if __name__ == '__main__': # If the canvas window has enlarged then some of the lines will have # to be extended. - canvas = Canvas(bg='black') canvas.bind('', handle_canvas_resize)