From 9e62a74af5e2963655df4802f27162892b80ae0e Mon Sep 17 00:00:00 2001 From: MikeTheWatchGuy Date: Sat, 14 Sep 2019 11:36:20 -0400 Subject: [PATCH] New demo program - demonstrates how to make a "rubber band" rectangle where you click and drag to draw it --- DemoPrograms/Demo_Graph_Drag_Rectangle.py | 53 +++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 DemoPrograms/Demo_Graph_Drag_Rectangle.py diff --git a/DemoPrograms/Demo_Graph_Drag_Rectangle.py b/DemoPrograms/Demo_Graph_Drag_Rectangle.py new file mode 100644 index 00000000..b23a795f --- /dev/null +++ b/DemoPrograms/Demo_Graph_Drag_Rectangle.py @@ -0,0 +1,53 @@ +import PySimpleGUI as sg + +""" + Demo - Drag a rectangle to draw it + + This demo shows how to use a Graph Element to (optionally) display an image and then use the + mouse to "drag a rectangle". This is sometimes called a rubber band and is an operation you + see in things like editors +""" + + +# image_file = r'Color-names.png' +image_file = None # image is optional + +layout = [[sg.Graph( + canvas_size=(400, 400), + graph_bottom_left=(0, 400), + graph_top_right=(400, 0), + key="-GRAPH-", + change_submits=True, # mouse click events + drag_submits=True),], + [sg.Text("", key="info", size=(60, 1))]] + +window = sg.Window("draw rect on image", layout, finalize=True) +# get the graph element for ease of use later +graph = window["-GRAPH-"] # type: sg.Graph + +graph.DrawImage(image_file, location=(0,0)) if image_file else None +dragging = False +start_point = end_point = prior_rect = None + +while True: + event, values = window.Read() + if event is None: + break # exit + if event == "-GRAPH-": # if there's a "Graph" event, then it's a mouse + x, y = values["-GRAPH-"] + if not dragging: + start_point = (x, y) + dragging = True + else: + end_point = (x, y) + if prior_rect: + graph.DeleteFigure(prior_rect) + if None not in (start_point, end_point): + prior_rect = graph.DrawRectangle(start_point, end_point, line_color='red') + elif event.endswith('+UP'): # The drawing has ended because mouse up + info = window.Element("info") + info.Update(value=f"grabbed rectangle from {start_point} to {end_point}") + start_point, end_point = None, None # enable grabbing a new rect + dragging = False + else: + print("unhandled event", event, values)