How to use PySimpleGui to make graphical interfaces

Let’s talk of this awesome module to make GUIs with Python.

Documentation can be found here

https://pysimplegui.readthedocs.io/en/latest/

The code for a simple window with text and buttons.





import PySimpleGUI as sg

layout = [[sg.Text('PythonProgrammi', font='_ 20')],
          [sg.Button('Hello'), sg.Button('Exit')]  ]

window = sg.Window('The PySimpleGUI Helpers', layout, icon=sg.EMOJI_BASE64_HAPPY_JOY, keep_on_top=True)

while True:             # Event Loop
    event, values = window.read()
    print(event, values)
    if event == sg.WIN_CLOSED or event == 'Exit':
        break
    elif event == 'Hello':
        sg.popup('Hi!', image="sg.png", keep_on_top=True)

window.close()
Bsically there is the layout (list of widgets), the call for the Window and the while loop for the user interactions

Integration with pygame

This is an example of how to integrate pygame and pysimplegui

import pygame
import PySimpleGUI as sg
import os

"""
    Demo of integrating PyGame with PySimpleGUI, the tkinter version
    A similar technique may be possible with WxPython
    To make it work on Linux, set SDL_VIDEODRIVER like
    specified in http://www.pygame.org/docs/ref/display.html, in the
    pygame.display.init() section.
"""
# --------------------- PySimpleGUI window layout and creation --------------------
layout = [[sg.Text('Test of PySimpleGUI with PyGame')],
          [sg.Graph((500, 500), (0, 0), (500, 500),
                    background_color='lightblue', key='-GRAPH-')],
          [sg.Button('Draw'), sg.Exit()]]

window = sg.Window('PySimpleGUI + PyGame', layout, finalize=True)
graph = window['-GRAPH-']

# -------------- Magic code to integrate PyGame with tkinter -------
embed = graph.TKCanvas
os.environ['SDL_WINDOWID'] = str(embed.winfo_id())
# change this to 'x11' to make it work on Linux
os.environ['SDL_VIDEODRIVER'] = 'windib'

# ----------------------------- PyGame Code -----------------------------

screen = pygame.display.set_mode((500, 500))
screen.fill(pygame.Color(255, 255, 255))

pygame.display.init()
pygame.display.update()

while True:
    event, values = window.read(timeout=10)
    if event in (sg.WIN_CLOSED, 'Exit'):
        pygame.quit()
    elif event == 'Draw':
        pygame.draw.circle(screen, (0, 0, 0), (250, 250), 125)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
    pygame.display.update()

window.close()

Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.