Pysimplegui 2020 Clearly Seeing A Gui For You: The Basic Questions: Who

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42
At a glance
Powered by AI
Some of the key takeaways from the document are that PySimpleGUI aims to be simple to use, provide Python-like APIs for building GUIs, and be cross-platform supporting Windows, Linux, Mac and more.

Some of the goals of PySimpleGUI are to get tasks done quickly, have fun, keep things simple, democratize GUIs, and provide success for users.

PySimpleGUI supports four primary GUI frameworks - tkinter, Qt, WxPython, and a Web port using Remi.

PySimpleGUI 2020

Clearly Seeing a GUI for You


“Simplicity is the ultimate sophistication” - Leonardo Da Vinci

The Basic Questions:


• Who
o Is it for? Students, beginners, experienced developers, non-
professional programmers, practical-programmers of all ages &
experience
o You - fellow developer, are the center of the PSG Universe. It
really is all about you and your success.
o Me - I’m Mike. Long history of commercial product development,
no prior GUI history (“avoided like the plague”). Newcomer to
Python. I don’t “know it all” but know a few things and like to
teach/share.
o User community – The PySimpleGUI users are awesome, helpful.
• What is PySimpleGUI?
o PySimpleGUI is a multi-OS, multi-GUI-framework Python package
o Windows, Linux, Mac, Raspberry Pi, Android using PyDroid3
o Open Source LGPL licensed, commercially managed project
Copyright April 2020 PySimpleGUI Page 1 of 42
o Intellectual Property from another (patent pending) product
o Written in Python, for Python, utilizing Python features
o If PySimpleGUI resonates with you great, it not, that’s OK there
are plenty of choices. There is no “right answer”.
o Simple describes the ease of working with PySimpleGUI, not the
problem space it can solve.
o Beautiful & magical
• When
o Released July 2018. PSG is young, still growing, not complete...yet.
• Where
o pip install from PyPI or copy single PySimpleGUI.py file
o http://www.PySimpleGUI.com GitHub
o http://www.PySimpleGUI.org The documentation
o http://Cookbook.PySimpleGUI.org Cookbook
o http://Trinket.PySimpleGUI.org PySimpleGUI in your browser
o http://Demos.PySimpleGUI.org long list of demos
• Why
o Had a practical need for a GUI
o Saw the magic and wanted to share
• How
o Uses a message passing architecture & converts to OOP arch
o Converts your calls into underlying GUI’s calls
o You are using the exact same underlying GUI widgets
• How Much / How Many
o 4 Primary ports – tkinter, Qt, WxPython Web (Remi)
o 1 .py file
o 845,000 pip installs
o 3,600 GitHub stars
o 1 developer + a few consultants & friends
o $0 – Your cost to use
o $0 – Your cost for support
Copyright April 2020 PySimpleGUI Page 2 of 42
o $0 – Your cost to say “thank you”
• Goals
o Get the job done… get from point A to point B
o Have fun
o Be simple (shockingly simple when possible)
o Democratize GUIs
o Provide Python-like APIs
o Up in 5 minutes
o Copy, Paste, Run
o Success after success
o Execute the vision
o Sustainability

Copyright April 2020 PySimpleGUI Page 3 of 42


IDEs are important
• PyCharm is preferred
• Spend a weekend on your IDE
• Setup colors
• Learn commands
o ^Q and ^P are your friends - docstrings
o SINGLE key run
o ^/ - Comment / uncomment line
o CTRL+ALT+SHIFT+INSERT – New scratch
• Can Use IDE instead of documentation for call signatures (tkinter
version)
• PyCharm and VS Code are the 2 officially supported IDEs. Others can
struggle with PySimpleGUI if they are tkinter based (e.g. IDLE).

Copyright April 2020 PySimpleGUI Page 4 of 42


Event Driven Vs Message
Passing Architectures
Python s Standard Library
Queue Library Architecture
Message
Source

Message
User Read request
Code
Reads Message
Queue

Message
Read a Queue
(Pull Model)

Copyright April 2020 PySimpleGUI Page 5 of 42


Traditional GUI - Event Driven (Push Model)
Button
Click

Button Click Event


Button 1
Code Button Click Event

Application GUI Library


(Dispatcher
Code Button 2 Button Click Event executes code)

Segmented Code
Into Callback
Functions Button Click Event
Button 3
Code

PySimpleGUI - Message Based (Pull Model)


Button
Click

Button Click Event


Button 1 Read request
Application Button 2 PySimpleGUI
Code
Code As Button 3 Save event info
Code
Linear Block Event Data
until user
reads

Button Click

Copyright April 2020 PySimpleGUI Page 6 of 42


Callbacks & Message Passing
How they “Feel to me”
Callbacks feel disjointed

Button Class Slider Class

Button click Slider


Callback Callback

Entry Class Button Class

Input
Button click
Changed
Callback
Callback

PySimpleGUI feels linear

Event Loop
If event == Button ’

If event == Button ’

If event == Slider

If event == Input

Copyright April 2020 PySimpleGUI Page 7 of 42


Installing
Via pip
• pip install PySimpleGUI
or
• pip3 install PySimpleGUI
GitHub
• Download PySimpleGUI.py and place in your application’s folder
• Use the new “upgrade from GitHub” tools

GitHub
• http://www.PySimpleGUI.com
• Latest code – Each port in a different folder with a readme
• Issues – Please use the Issue Form
• Demos – Universal folder and per-port folders

Copyright April 2020 PySimpleGUI Page 8 of 42


The PySimpleGUI “System”
Pieces designed to work together for a positive experience
Trinket – The 00,000 foot view. Get a “taste” without installing.
http://Trinket.PySimpleGUI.org
Main Docs - http://www.PySimpleGUI.org
• Learn it, Love it, Live it
• Too much?
o Sidebar Table of Contents
o Use Control+F
o Last sections have call signatures
• Mainly covers tkinter port. Separate readme for each port on GitHub
Cookbook – “Your Recipe for Success” http://Cookbook.PySimpleGUI.org
Demos - http://Demos.PySimpleGUI.org
• Teaches you coding conventions, style and techniques
• Per Element usage
• Integration to other packages
• Primary list sometimes runs on multiple ports

Copyright April 2020 PySimpleGUI Page 9 of 42


Coding Conventions
By following a coding convention, PySimpleGUI users can understand each
other’s code quickly. It gives us all a “common language” to speak.

The primary suggested conventions are:

• import PySimpleGUI as sg
• Name your Window window
• Read your window into variables event and values
• Name your layout layout
• Use window[key] to lookup elements
• For keys that are strings, follow the pattern '-KEY-'

All of these can be seen in this short program:


import PySimpleGUI as sg

layout = [ [sg.Text('My Window')],


[sg.Input(key='-IN-')],
[sg.Text(size=(20,1), key='-OUT-')],
[sg.Button('Go'), sg.Button('Exit')] ]

window = sg.Window('Window Title', layout)

while True: # Event Loop


event, values = window.read()
print(event, values)
if event in (None, 'Exit'):
break
if event == 'Go':
window['-OUT-'].update(values['-IN-'])
window.close()

Copyright April 2020 PySimpleGUI Page 10 of 42


Coding Tips
• Stay simple at every opportunity
• Read or search the documentation (http://www.PySimpleGUI.org)
• Use the coding conventions
• Write compact layouts
• Use the PEP8 bindings
• Use "user defined elements" when you find yourself repeating
parameters many times (functions that return elements)
• Use PySimpleGUI constructs rather than other GUI frameworks'
constructs
• Use reasonable timeout values (as large of non-zero values as
possible... be a good CPU citizen)
• Do not try to make any PySimpleGUI call from a thread
• Close your windows before exiting
• Make linear event loops
• Use the values dictionary rather than Element.get() methods
• Look through Demo Programs for more tips / techniques
(http://Demos.PySimpleGUI.org)

Copyright April 2020 PySimpleGUI Page 11 of 42


Popups
The high-level input/output mechanism.
In a GUI they can replace input and print (there often is no console)
There are a lot of them, and a lot of options.
If you’re thinking of filing an enhancement request for popup:
• Don’t

• Congratulations, it’s time you learn how to make your own windows

Can be duplicated in 1 line of code.


Good for adding a frontend onto a command line program

Copyright April 2020 PySimpleGUI Page 12 of 42


There are a lot of them

Input popups

Particularly good to use on frontends that need a filename as a parameter.

Copyright April 2020 PySimpleGUI Page 13 of 42


One Line Progress Meter
Like popup, another single-line high level call.
Provides an window filled with progress stats by adding a single line to your
loop.
Unlike tqdm and others, no “setup”, no changes to your loop itself, just add
a line of code.
Also provides the ability to cancel the operation.

Copyright April 2020 PySimpleGUI Page 14 of 42


Design Patterns
“Design Patterns” provide a skeleton for you to build upon. They are not
only for basic PySimpleGUI windows, but also specific topics like multi-
threading, integrating with packages like OpenCV.

Two Basic PySimpleGUI


Design Patterns
In main documentation, Cookbook,
1. “One Shot” – A window that is read one time and then closed
2. “Persistent” – A window that hangs around for a while. A user interacts
with it on an ongoing basis

“One Shot” programs lack “Event Loops” and can be 1 line of code.

Copyright April 2020 PySimpleGUI Page 15 of 42


PySimpleGUI Program
Anatomy
5 sections of every PySimpleGUI program
1. Import
2. Layout
3. Window
4. Event Loop (optional)
5. Close

# 1 - The import
import PySimpleGUI as sg

# 2 - Layout definition
layout = [[sg.Text('My layout')],
[sg.Input(key='-INPUT-')],
[sg.Button('OK'), sg.Button('Cancel')] ]

# 3 - Create window
window = sg.Window('Design Pattern 3 - Persistent Window', layout)

# 4 - Event Loop
while True:
event, values = window.read()
if event in (None, 'Cancel'):
break

# 5 - Close window
window.close()

Copyright April 2020 PySimpleGUI Page 16 of 42


# 1 - The import
1 – Import
import PySimpleGUI as sg
import PySimpleGUIQt as sg
import PySimpleGUIWx as sg
import PySimpleGUIWeb as sg

• There are currently 4 ports of PySimpleGUI, each at a different level of


completeness
o PySimpleGUI – tkinter port. Most completed. Gets the most
attention and new features first
o PySimpleGUIQt – PySide2 port. Almost but not quite to feature
complete. Supports System Tray
o PySimpleGUIWeb – Remi port. Engineering release.
o PySimpleGUIWx – WxPython port. Engineering release. Supports
System Tray
• Moving between ports can be as simple as changing the import.
Sometimes that’s all that’s required.
• Changes needed depends on features used.
o Some features like right click menu aren’t supported across all
ports
o Sizes are measured differently – crude conversion formula to go
from (char, rows) to (pixels, pixels)
• Never, ever:
o from PySimpleGUI import *
o Triggers an auto-delete of the .py file attempting the import (it’s a
joke… it doesn’t delete your file…. Just don’t do it please)

Copyright April 2020 PySimpleGUI Page 17 of 42


2- Layout
The “Layout” defines the look of your window
Layouts are lists of lists of Elements (as in “Atoms”). Piece them together
into a molecule. Add control logic and you’ve got an organism, a standalone
functioning creation.
Each list in the layout represents a “row” in your window
Each row is a list of Elements
• “Elements” are PySimpleGUI’s “Widgets”.
• “Widget” refers to the underlying GUI’s implementation
• A Text Element is implemented using tkinter’s Label Widget
• A Spin Element is tkinter’s Spinbox, WxPython’s SpinButton, Qt’s
QSpinBox, Remi’s SpinBox

# 2 - Layout definition
layout = [[sg.Text('My layout')],
[sg.Input(key='-INPUT-')],
[sg.Button('OK'), sg.Button('Cancel')] ]

Creates this window

Copyright April 2020 PySimpleGUI Page 18 of 42


Layout Designer
Layouts are designed to be visual representations of your window, reducing
the need for a “Designer”.
The “built-in” designer:
1. Launch the designer

2. Sketch your window

3. Divide into “rows” and label the Elements

Copyright April 2020 PySimpleGUI Page 19 of 42


Copyright April 2020 PySimpleGUI Page 20 of 42
4. Label the elements

5. Write the layout code


layout = [[sg.Text('Enter a Number')],
[sg.Input()],
[sg.OK()] ]

6. Add layout to your program and execute


import PySimpleGUI as sg

layout = [[sg.Text('Enter a Number')],


[sg.Input()],
[sg.OK()] ]

window = sg.Window('Enter a number example', layout)


event, values = window.read()
window.close()

Copyright April 2020 PySimpleGUI Page 21 of 42


Elements
• Text
• Single Line Input
• Buttons (multiple “types”)
• ButtonMenu
• Checkboxes
• Radio Buttons
• Listbox
• Slider
• Multi-line Text Input/Output
• Multi-line Text Output (not on tkinter version)
• Scroll-able Output
• Vertical Separator
• Progress Bar
• Option Menu
• Menu
• Graph
• Image
• Table
• Tree
• StatusBar
• Stretch (Qt only)
• Sizer (tkinter only)
• Containers
o Column

o Frame

o Tab, TabGroup

o Pane

Copyright April 2020 PySimpleGUI Page 22 of 42


Element Options
Elements are “configured in place” using long list of parameters.
Sometimes you don’t need to name each parameter in PySimpleGUI calls.
Common element parameters
• Size
• Key
• Font
• Pad
• Colors
• Enable Events
• Visibility
• Tooltip
• Metadata
• Right click menu (tkinter)
Use your IDE’s superpowers to get a list of available parameters.
Docstrings are awesome too.

Copyright April 2020 PySimpleGUI Page 23 of 42


Call signatures for all elements in docs http://www.PySimpleGUI.org

Copyright April 2020 PySimpleGUI Page 24 of 42


3 – Window Creation
window = sg.Window('Window Title', layout)

Like Elements, has a lot of options.

Some parameters are used to configure elements (a window-level setting)

Copyright April 2020 PySimpleGUI Page 25 of 42


“Reading” Windows
event,values = window.read()
This one line of code summarizes how PySimpleGUI differs from the other
GUI Frameworks.
Calling Window.read() displays the window on the screen if it’s not
been displayed. “Finalizing” a window also displays it.
The call blocks / pends until an event happens.

As can be seen, 2 items are returned


1. The event that caused the read to return
2. The “values dictionary”
event
The most common event is a button click.
If events are enabled for an element, that element can generate an event.
An element’s “key” is returned as the event.
values
Dictionary containing values of all elements in the window.
You do not need to call “get” methods to get the latest values. They are all
in the values variable.
If a simple window and no keys are specified, then will be a List.

Copyright April 2020 PySimpleGUI Page 26 of 42


“One Shot” Windows Have
No Event Loop
“Get some information and move on”.
These windows you read one time and then close.
They can be a single line of code by using the read() parameter close=True.
Useful as frontends for converting a command line tool to GUI based.

Copyright April 2020 PySimpleGUI Page 27 of 42


4 - Event Loop
Used for “persistent windows”.
In other frameworks the event loop is part of the framework.
In PySimpleGUI your code is the event loop.
A basic event loop:
while True:
event, values = window.read()
if event in (None, 'Exit'):
break
Always check for None so that users can exit the program. Otherwise
program will continue to run in the background forever or will crash after
window is closed with “X”
Inside your event loop:
• Check for events and handle
• Output to window by “updating” elements
• Perform any other I/O or operations you need to do
Must call window.read or window.refresh frequently or Windows
will complain that your application had become “unresponsive”
Lengthy operations need to be broken out into threads, but you cannot call
PySimpleGUI from a thread. There are numerous demos for how to do this.
Can be a simple series of “if statements” checking for events. If the number
of events being handled is large, then a simple dispatcher can be used.
if event == 'Go':
start_motor()
elif event == 'Stop':
stop_motor()
else:
print('Unexpected event')

Copyright April 2020 PySimpleGUI Page 28 of 42


5 – Close Window
window.close()

When done with a window, close it


Exiting your program will close windows for some ports
If you don’t close a PySimpleGUIWeb window, your program will not exit

Copyright April 2020 PySimpleGUI Page 29 of 42


Changing Window Contents
Element.update()
To change your window’s contents, call update method for the element
A window must first be read or finalized prior to changing any
element
To change an element, first locate the element. Use the element’s key:
window[key]
The old format was
window.find_element(key)
Call the update method to change something about the element
window[key].update(‘New value’)
Each element has a different set of things that can be changed/updated
See the documentation/IDE for details on each element
First parameter is almost always the “value” of the element (text, button
text, checked/unchecked, etc.)

Copyright April 2020 PySimpleGUI Page 30 of 42


Shortcuts & Code
Compression
Elements have one of more shortcuts
• Text, Txt, T
• InputText, Input, In, I
Window.FindElement replaced with Window[]
Two little-known / rarely used shortcuts
• “Calling” a window object same as Window.read
• “Calling” an element object same as Element.update
Compressing code is often a multi-pass activity
“User Defined Elements”
• Functions that return Elements
• Use to avoid copying and pasting long element definitions
• Can create entire layouts also

Copyright April 2020 PySimpleGUI Page 31 of 42


Button Targets
The “chooser” Buttons have targets that are filled in with your choice.
Chooser buttons include:
• FileBrowse
• FilesBrowse
• FileSaveAs
• FolderBrowse
• ColorChooserButton
• CalendarButton
The default is the element to the Button’s left.

Copyright April 2020 PySimpleGUI Page 32 of 42


Window Beautification
Tkinter windows are not “ugly” by default.
“Beautiful” windows don’t just happen. There is a reason companies have
graphic designers.
But, themes can give you a running start at a nice looking GUI.
There are over 40 “themes” available….. use them!

If you don’t like the buttons, make your own.


Experiment with no titlebar, alpha channel, padding, themes, custom
graphics, etc.
Theme names can be guessed until you find one you like (e.g. “Dark Green
3”)
Rainmeter style widgets – no titlebar + grab anywhere + alpha channel
Embed your graphics in your source code
• Base64 graphics
• Demo programs available to make it easy (Demo_Base64_...)
Copyright April 2020 PySimpleGUI Page 33 of 42
Container Elements
These elements hold other elements, usually in the format of a layout (a list
of lists).
Container elements include:
• Column
• Frame
• Tab, TabGroup
• Pane
Use Columns:
• When horizontal alignment is needed
• To place multiple elements beside a large single element
• As a placeholder for “Invisible” elements
• To align elements center and right
• When you need multiple groups of element (e.g. many graphs)

Usually takes same list of lists as a “layout”

Copyright April 2020 PySimpleGUI Page 34 of 42


Building Layouts
Because Windows are defined using lists, it’s easy to make windows
programmatically.
Use list comprehensions to create Layouts.
This is a “Single-Line-Sudoku”

sg.Window('Sudoku',[[sg.Frame('',[[sg.I(random.randint(1,9), justification='r',
size=(3,1),key=(frow*3+row,fcol*3+col)) for col in range(3)] for row in range(3)]) for
fcol in range(3)] for frow in range(3)]+ [[sg.B('Exit')]]).read()

“Add” together lists to create a layout

Copyright April 2020 PySimpleGUI Page 35 of 42


Async Windows
If you need to do something periodically, then run your window with a
timeout.
Example uses:
• Stopwatch / timer
• Scraping web pages
• Polling hardware
• Servicing queues
• Multi-threaded
• Multi-window applications (Round-robin scheduling)
• Animations
• Built-in debugger
To run a window asynchronously, add a timeout to the window.read()
call
Be a good corporate citizen
• Keep timeout values reasonable
• Low timeout values will consume your CPU’s core
• 00 ms is reasonable. 5 ms isn’t.
• 0 can be used, but please make sure it’s required

Copyright April 2020 PySimpleGUI Page 36 of 42


System Tray Icon
Run your program in the background and show as icon in the system tray
A System Tray Icon feature is available for Wx and Qt ports
For tkinter port the same SystemTray APIs exist, but instead of system tray,
it creates a “super-icon” on the desktop.
Uses same “read” call and architecture that windows have.
Features include:
• Right click menu
• Single icon click event
• Double icon click event
• Display message in tray
• Message clicked event
• Change icon
• Runs in blocking or async mode (just like windows)

Copyright April 2020 PySimpleGUI Page 37 of 42


System Tray (cont)
Qt & Wx – Lives in the tray

Tk – Lives on the “desktop” (actually a floating window)

Copyright April 2020 PySimpleGUI Page 38 of 42


Debugger
PySimpleGUI (tkinter port) has the “Live REPL” (ImWatchingYou package)
built-in.
Can make explicit calls to show the windows
sg.show_debugger_window()
sg.show_debugger_popout_window()
Or use the Break / Control+Break keys (pop-out, main window)

Copyright April 2020 PySimpleGUI Page 39 of 42


Extending
It’s possible to “extend” PySimpleGUI’s capabilities by directly accessing the
underlying GUI framework’s widget.
The member variable Element.Widget contains the widget that is used
to implement the element.
If you want to access the widget for element with key ‘-KEY-’:
Window[‘-KEY-‘].Widget
With tkinter this is usually done to access a configuration setting that’s not
been exposed through PySimpleGUI.
Window[‘-KEY-‘].Widget.config(setting=1234)
To convert a normal progress bar into an indeterminate one:
window['bar'].Widget.config(mode='indeterminate')

Copyright April 2020 PySimpleGUI Page 40 of 42


Support
Only provided on GitHub
Don’t be afraid to ask questions.
Don’t suffer silently.
Fill out the Issue form
“Help me help you”
Today’s support cost is the same pricing as the introduction pricing of $0
It’s easy to find missing features. Generally speaking logging them isn’t
helpful. Same with “it would be better if it was architected this way”
Enhancement Algorithm & Hurdles
• Is it impossible to do using existing APIs
• Is it an “80% feature”
• Does it fit the PySimpleGUI vision
• Some decisions may not feel right to you
• This is not a typical Open Source project
• There is a vision and a priority order for working on fixes /
enhancements. It’s not possible to fully explain the process on paper
Please don’t submit code
• No pull requests accepted
• If you notice a 5 or 10 line fix, then OK to put in the Issue you file

Copyright April 2020 PySimpleGUI Page 41 of 42


Thank you!
A warm “Thank You!” to the users and supports of PySimpleGUI over the
past 2 years. Your support is greatly appreciated. You’ve helped make
PySimpleGUI what it is today. It couldn’t have come this far without your
help and support.

Copyright April 2020 PySimpleGUI Page 42 of 42

You might also like