Cache x y to deal with resizing canvas.
This commit is contained in:
parent
8eab96431d
commit
b04472619b
20
reticule.py
20
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(
|
||||
'<Configure>',
|
||||
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('<Configure>', handle_canvas_resize)
|
||||
|
|
|
|||
Loading…
Reference in New Issue