Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.

15 St Margarets, NY 10033
(+381) 11 123 4567



PySimpleGUI: How to Draw Shapes on an Image With a GUI

from PIL import Image, ImageColor, ImageDraw

file_types = [("JPEG (*.jpg)", "*.jpg"), ("All files (*.*)", "*.*")]

tmp_file = tempfile.NamedTemporaryFile(suffix=".jpg").name

def get_value(key, values):

        return int(value)

def apply_drawing(values, window):

    image_file = values["-FILENAME-"]

    shape = values["-SHAPES-"]

    begin_x = get_value("-BEGIN_X-", values)

    begin_y = get_value("-BEGIN_Y-", values)

    end_x = get_value("-END_X-", values)

    end_y = get_value("-END_Y-", values)

    width = get_value("-WIDTH-", values)

    fill_color = values["-FILL_COLOR-"]

    outline_color = values["-OUTLINE_COLOR-"]

    if os.path.exists(image_file):

        shutil.copy(image_file, tmp_file)

        image = Image.open(tmp_file)

        image.thumbnail((400, 400))

        draw = ImageDraw.Draw(image)

        if shape == "Ellipse":


                (begin_x, begin_y, end_x, end_y),




        elif shape == "Rectangle":


                (begin_x, begin_y, end_x, end_y),





        bio = io.BytesIO()

        image.save(bio, format="PNG")


def create_coords_elements(label, begin_x, begin_y, key1, key2):


        sg.Input(begin_x, size=(5, 1), key=key1, enable_events=True),

        sg.Input(begin_y, size=(5, 1), key=key2, enable_events=True),

    save_filename = sg.popup_get_file(

        "File", file_types=file_types, save_as=True, no_window=True

    if save_filename == values["-FILENAME-"]:


            "You are not allowed to overwrite the original image!")

        if save_filename:

            shutil.copy(tmp_file, save_filename)

            sg.popup(f"Saved: {save_filename}")

    colors = list(ImageColor.colormap.keys())


            sg.Text("Image File"),


                size=(25, 1), key="-FILENAME-"


            sg.Button("Load Image"),



                ["Ellipse", "Rectangle"],






                "Begin Coords", "10", "10", "-BEGIN_X-", "-BEGIN_Y-"


                "End Coords", "100", "100", "-END_X-", "-END_Y-"
















            sg.Input("3", size=(5, 1), key="-WIDTH-", enable_events=True),


    window = sg.Window("Drawing GUI", layout, size=(450, 500))



        event, values = window.read()

        if event == "Exit" or event == sg.WIN_CLOSED:

        if event in events:

            apply_drawing(values, window)

        if event == "Save" and values["-FILENAME-"]:


if __name__ == "__main__":

Credit: Source link

Previous Next
Test Caption
Test Description goes like this