Fast Crashcourse on PySimpleGui

https://realpython.com/pysimplegui-python/ https://pypi.org/project/PySimpleGUI/

Install:

pip install pysimplegui

Imports:

import PySimpleGUI as sg

Simple Gui:

Let’s create a layout and a button in it. We’ll do this in 4 baby steps:

  • We’re gonna import the necessary library

  • We’ll create a layout in list format with brackets: [ ]

  • We’ll use sg.Button() method and put it inside the layout.

  • Then we’ll create a window using sg.Window() which takes

    • a title string

    • layout object

  1. Import:

import PySimpleGUI as sg
  1. Create layout with button in it:

layout = [[sg.Button('Hello World')]]
  1. Create the window with a title and the layout we created earlier:

window = sg.Window('Push my Buttons', layout)
  1. Reading the window to make it show up:

event, values = window.read()

What we have done:

GUI Size Settings (Layout Size, Button Size, Font Size etc.)

You can simply add tuples of size parameters to both the sg.Button and sg.Window. It works so: size(width, height)

import PySimpleGUI as sg
layout  = [[sg.Button('Hello World', size=(20,4))]]
window = sg.Window('Push my Buttons', layout, size=(200,150))
event, values = window.read()

What we have done:

GUI Alignment Tricks (Row Alignment, Column Alignment)

You can simply add sg.T or sg.Text methods to add a text or add blank strings to move the buttons Left and Right:

layout = [[sg.Text("Primary Button: "), sg.Button('Hello World',size=(20,4))]]
window = sg.Window('Bunch of Buttons', layout, size=(270,100))

What we have done:

So, here is the trick, inside the same bracket we’re altering the same row. Create new brackets and you’ll be creating new rows which can be used to alter column alignment. Let’s use sg.T this time and a string with blanks to create space above the button:

Note: Also pay attention to the windows size we’re changing that to create a more suitable window for the layout.

layout = [[sg.T("")], [sg.Button('Hello World',size=(20,4))]]
window = sg.Window('Push my Buttons', layout, size=(210,150))

What we have done:

Themes (Prettify GUI real quick)

PySimpleGUI has great color themes that you can apply to your program to make things a little more colorful (or sometimes less) These theme colors are really well prepared and makes styling so much easier.

We will use sg.theme() method to implement various colors to the GUI window.

import PySimpleGUI as sg
sg.theme('Reddit')
layout = [[sg.Text("Primary Button: "), sg.Button('Hello World',size=(20,4))]]
window = sg.Window('Push my Buttons', layout, size=(270,100))
event, values = window.read()

What we have done:

Here is a look at:

LightYellow DarkBlue15 Tan DarkTeal2 Topango LightBrown5

Here are some more ideas to check out: Black TealMono TanBlue LightGreen1 LightGreen2 LightGreen3 LightGreen4 DarkBlue15 Tan SystemDefault LightBlue5 LightBrown DarkPurple DarkGreen LightPurple LightGrey Green Dark BrownBlue BrightColors BlueMono BluePurple DarkRed DarkBlack

All Themes can be found here

How to tie buttons to functions? (Action time)

Now, if you’re creating buttons you’ll likely want them to execute something. That’s the whole point right. We can simply create user defined functions or map Python’s builtin functions to the buttons we create with the PySimpleGUI library.

So, mapping buttons to functions is not that complicated. You just need some basic loop knowledge in Python. Please feel free to these materials if you need to polish your For Loop and While Loop knowledge.

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
    elif event == 'Hello World!':
        print("Hello World!")

So what’s going on in this code snippet?

  • Firstly, everything is structured inside an infinite while loop. This way GUI interface is continuously monitored and executions are carried out when needed.

  • GUI windows is being monitored with .read() method. This means every time a button is pressed or a selection is made those values can be interpreted by the program.

  • if statement ensures that program is closed when close button is pressed. This is achieved by break statement. If you need a primer on that we have a great lesson focusing on break statement and its cousin try/except statement can be useful as well.

  • elif statements manage each action that needs to be done when event equals buttons name.

    • This is stated as:

elif event == "Hello World!":

Checkboxes and Radio Buttons (w/ Implementation and Examples)

  1. Checkbox Example with PySimpleGUI (Python Implementation)

Often, software requires additional input from the user and main mechanisms are coded to be able to respond to those preferences. In this case, boolean selection items such as radio buttons or checklists become incredibly useful. In principal:

  • Radio buttons are used when either one of the options must be selected

  • Checklist boxes are used when either one or more options can either be checked or left unchecked.

In either case the options will be represented as True or False based on the input and this can be used as input to your code and particularly conditional statements in your code. There are probably infinite cases but some examples from the top of my head are:

Possible Checklist Boxes:

  • Red | Green | Blue | Black | White

  • Italic | Bold | Underline | Strike

These are just some simple probable examples from real life.

You can assigne a title and a default boolean state (here it’s True)

[sg.Checkbox('My Checkbox', default=True)]

Here is the full code for a centered button with a checkbox which has default False state:

import PySimpleGUI as sg
layout = [[sg.T("")],[sg.T("        "), sg.Button('Hello World',size=(20,4))], [sg.T("")],
          [sg.T("                   "), sg.Checkbox('Print On:', default=True)]]

###Setting Window
window = sg.Window('Push my Buttons', layout, size=(300,200))

###Showing the Application, also GUI functions can be placed here.
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event=="Exit":
        break
    
window.close()

Input value can be acquired by adding a key parameter inside items like this:

layout = [[sg.Button('Hello World',size=(20,4))],
          [sg.Checkbox('Print On:', default=False, key="-IN-")]]

When we read the window as: event, values = window.read() keys will be stored in the values. Now, “-IN-“ is this checkbox’ key. We will be able to look up checkbox’ value with this key. This checkbox can particularly be read with: values["-IN-"]

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event=="Exit":
        break
    elif values["-IN-"] == True:
        print("Hello World")

Full code:

import PySimpleGUI as sg
layout = [[sg.T("")],[sg.T("        "), sg.Button('Hello World',size=(20,4))], [sg.T("")],
          [sg.T("                   "), sg.Checkbox('Print On:', default=True, key="-IN-")]]

###Setting Window
window = sg.Window('Push my Buttons', layout, size=(300,200))

###Showing the Application, also GUI functions can be placed here.

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event=="Exit":
        break
    elif values["-IN-"] == True:
        print("Hello World")
    
window.close()

Radio Button Example with PySimpleGUI

Possible Radio Buttons:

  • Big | Small

  • Encrypted | Not encrypted

  • Attachment | No attachment

  • Receipt | No Receipt

  • Private | Public

  • Am | Fm | Longwave | Shortwav

[sg.Radio('Permission Granted', "RADIO1", default=False)],
[sg.Radio('Permission not Granted', "RADIO1", default=True)]

Let’s build on the first example. Let’s say it only prints if the checkbox is checked plus if the “Permission Granted” radio button is selected. I’m defining keys as -IN-, -IN2- to have a system. You can assign pretty much any string value to them.

import PySimpleGUI as sg
layout = [[sg.T("")],[sg.T("        "), sg.Button('Hello World',size=(20,4))], [sg.T("")],
          [sg.T("         "), sg.Checkbox('Print On:', default=True, key="-IN-")],
          [sg.T("         "), sg.Radio('Permission Granted', "RADIO1", default=False, key="-IN2-")],
          [sg.T("         "), sg.Radio('Permission not Granted', "RADIO1", default=True)]]

###Setting Window
window = sg.Window('Push my Buttons', layout, size=(300,300))

###Showing the Application, also GUI functions can be placed here.

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event=="Exit":
        break
    elif values["-IN-"] == True and values["-IN2-"] == True:
        print("Hello World")
    
window.close()

Last updated