2

I am looking to draw a rectangle on an Image using Pysimplegui. I have tried to do it using the Graph object but as far as I know you can not do anything on an image object. I found an alternative in Pygame but my script is already built up to this point in pysimplegui. Does this functionailty/demo exist?

Tylerr
  • 201
  • 2
  • 12

1 Answers1

5

Draw the image into the graph object, then draw the rect on top:

import PySimpleGUI as sg

layout = [
    [
        sg.Graph(
            canvas_size=(400, 400),
            graph_bottom_left=(0, 0),
            graph_top_right=(400, 400),
            key="graph"
        )
    ]
]

window = sg.Window("rect on image", layout)
window.Finalize()

graph = window.Element("graph")

graph.DrawImage(filename="foo.png", location=(0, 400))
graph.DrawRectangle((200, 200), (250, 300), line_color="red")

while True:
    event, values = window.Read()
    if event is None:
        break
Finlay McWalter
  • 1,222
  • 1
  • 10
  • 12
  • Ok awesome, this is what I thought might have to happen. I should have been clearer with one aspect: is it possible to have someone actually draw the rectangle? I guess use mouse events? – Tylerr Jul 24 '19 at 23:03
  • The Graph Element is capable of sending back mouse movement events, both click and drag events. The docs talk about DrawImage, but don't show the detailed call signature yet https://pysimplegui.readthedocs.io/en/latest/#graph-element. Docs are mid-update. – Mike from PSG Jul 25 '19 at 13:13
  • 1
    Well, I got a bit carried away and implemented something like you describe (a rubber-rect drawn over an image, while we drag it around to "select" part of the image). I used PIL to do the drawing (as I can't seem to find double-buffering support in PySimpleGUI). Unfortunately, at least for me, PySimpleGUI isn't reporting mouse-button-up events when it has mouse move events also enabled - without that, it's not reliable. I've raised a github issue: https://github.com/PySimpleGUI/PySimpleGUI/issues/1738 – Finlay McWalter Jul 25 '19 at 18:54
  • The maintainer of PySimpleGUI has added some additional mouse event handling, which now makes proper drag-and-release interactive drawing work great in PySimpleGUI. It's in the GIT version now, and will be in the next version he pushes to pip. The github issue I linked above has a piece of demo code that displays and image and lets you drag a "rubber rectangle" over it, which it seems is just what you want. – Finlay McWalter Aug 11 '19 at 20:49
  • Absolutely amazing! This will definitely add some awesome functionality to pysimplegui. Cheers! – Tylerr Aug 13 '19 at 18:50