Create, Move, and Erase Shapes in PySimpleGUI Dynamically

Posted by

PySimpleGUI – Dynamically Create, Move, and Erase Shapes

PySimpleGUI – Dynamically Create, Move, and Erase Shapes

PySimpleGUI is a Python library that allows you to create GUI applications in a simple and intuitive way. One of the features of PySimpleGUI is the ability to dynamically create, move, and erase shapes on the GUI.

Creating Shapes

To create a shape in PySimpleGUI, you can use the draw_line(), draw_rectangle(), or draw_circle() functions. These functions allow you to define the position, size, and color of the shapes that you want to create.

“`python
import PySimpleGUI as sg

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

window = sg.Window(‘Drawing Shapes’).Layout(layout)

graph = window.Element(‘graph’)

while True:
event, values = window.Read()

if event is None:
break

if event == ‘graph’:
graph.DrawPolygon(points=[(0,0), (50,0), (30,30)], line_color=’black’, fill_color=’red’)
“`

Moving Shapes

Once you have created a shape, you can move it by changing its position. PySimpleGUI provides the move_figure() function, which allows you to specify the shape to move and its new position.

“`python

if event == ‘Move’:
graph.move_figure(1, 20, 20)

“`

Erasing Shapes

To erase a shape from the GUI, you can use the delete_figure() function. This function takes the ID of the shape to delete as its argument.

“`python

if event == ‘Erase’:
graph.delete_figure(1)

“`

With PySimpleGUI, creating, moving, and erasing shapes on a GUI is straightforward and can add interactivity and visual interest to your applications.