2019-09-14 15:36:20 +00:00
|
|
|
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'
|
2019-12-24 23:52:47 +00:00
|
|
|
# image_file = None # image is optional
|
|
|
|
image_file = r'C:\Python\PycharmProjects\GooeyGUI\logo200.png' # image is optional
|
2019-09-14 15:36:20 +00:00
|
|
|
|
|
|
|
layout = [[sg.Graph(
|
2019-12-24 23:52:47 +00:00
|
|
|
canvas_size=(400, 400),
|
|
|
|
graph_bottom_left=(0, 0),
|
|
|
|
graph_top_right=(400, 400),
|
|
|
|
key="-GRAPH-",
|
|
|
|
change_submits=True, # mouse click events
|
|
|
|
background_color='lightblue',
|
|
|
|
drag_submits=True), ],
|
|
|
|
[sg.Text(key='info', size=(60, 1))]]
|
2019-09-14 15:36:20 +00:00
|
|
|
|
|
|
|
window = sg.Window("draw rect on image", layout, finalize=True)
|
|
|
|
# get the graph element for ease of use later
|
2019-12-24 23:52:47 +00:00
|
|
|
graph = window["-GRAPH-"] # type: sg.Graph
|
2019-09-14 15:36:20 +00:00
|
|
|
|
2019-12-24 23:52:47 +00:00
|
|
|
graph.draw_image(image_file, location=(0,400)) if image_file else None
|
2019-09-14 15:36:20 +00:00
|
|
|
dragging = False
|
|
|
|
start_point = end_point = prior_rect = None
|
|
|
|
|
|
|
|
while True:
|
2019-10-23 20:10:03 +00:00
|
|
|
event, values = window.read()
|
|
|
|
|
2019-09-14 15:36:20 +00:00
|
|
|
if event is None:
|
|
|
|
break # exit
|
2019-12-24 23:52:47 +00:00
|
|
|
|
|
|
|
if event == "-GRAPH-": # if there's a "Graph" event, then it's a mouse
|
2019-09-14 15:36:20 +00:00
|
|
|
x, y = values["-GRAPH-"]
|
|
|
|
if not dragging:
|
|
|
|
start_point = (x, y)
|
|
|
|
dragging = True
|
|
|
|
else:
|
|
|
|
end_point = (x, y)
|
|
|
|
if prior_rect:
|
2019-10-23 20:10:03 +00:00
|
|
|
graph.delete_figure(prior_rect)
|
2019-09-14 15:36:20 +00:00
|
|
|
if None not in (start_point, end_point):
|
2019-10-23 20:10:03 +00:00
|
|
|
prior_rect = graph.draw_rectangle(start_point, end_point, line_color='red')
|
2019-12-24 23:52:47 +00:00
|
|
|
|
|
|
|
elif event.endswith('+UP'): # The drawing has ended because mouse up
|
2019-10-23 20:10:03 +00:00
|
|
|
info = window["info"]
|
|
|
|
info.update(value=f"grabbed rectangle from {start_point} to {end_point}")
|
2019-12-24 23:52:47 +00:00
|
|
|
start_point, end_point = None, None # enable grabbing a new rect
|
2019-09-14 15:36:20 +00:00
|
|
|
dragging = False
|
2019-12-24 23:52:47 +00:00
|
|
|
|
2019-09-14 15:36:20 +00:00
|
|
|
else:
|
|
|
|
print("unhandled event", event, values)
|