You'll find that starting with a Recipe will give you a big jump-start on creating your custom GUI. Copy and paste one of these Recipes and modify it to match your requirements. Study them to get an idea of what design patterns to follow.
The Recipes in this Cookbook all assume you're running on a Python3 machine. If you are running Python 2.7 then your code will differ by 2 character. Replace the import statement:
import PySimpleGUI as sg
with
import PySimpleGUI27 as sg
There is a short section in the Readme with instruction on installing PySimpleGUI
## Simple Data Entry - Return Values As List
Same GUI screen except the return values are in a list instead of a dictionary and doesn't have initial values.
Quickly add a GUI allowing the user to browse for a filename if a filename is not supplied on the command line using this 1-line GUI. It's the best of both worlds.
[sg.Text('All graphic widgets in one window!', size=(30, 1), justification='center', font=("Helvetica", 25), relief=sg.RELIEF_RIDGE)],
[sg.Text('Here is some text.... and a place to enter text')],
[sg.InputText('This is my text')],
[sg.Frame(layout=[
[sg.Checkbox('Checkbox', size=(10,1)), sg.Checkbox('My second checkbox!', default=True)],
[sg.Radio('My first Radio! ', "RADIO1", default=True, size=(10,1)), sg.Radio('My second Radio!', "RADIO1")]], title='Options',title_color='red', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set flags')],
[sg.Multiline(default_text='This is the default Text should you decide not to type anything', size=(35, 3)),
sg.Multiline(default_text='A second multi-line', size=(35, 3))],
An async Window that has a event read loop. A Text Element is updated periodically with a running timer. Note that `value` is checked for None which indicates the window was closed using X.
if values is None or event == 'Quit': # if user closed the window using X or clicked Quit button
break
elif event == 'Start/Stop':
timer_running = not timer_running
window.FindElement('output').Update('{:02d}:{:02d}.{:02d}'.format((i // 100) // 60, (i // 100) % 60, i % 100))
time.sleep(.01)
--------
## Callback Function Simulation
The architecture of some programs works better with button callbacks instead of handling in-line. While button callbacks are part of the PySimpleGUI implementation, they are not directly exposed to the caller. The way to get the same result as callbacks is to simulate them with a recipe like this one.
This recipe implements a remote control interface for a robot. There are 4 directions, forward, reverse, left, right. When a button is clicked, PySimpleGUI immediately returns button events for as long as the buttons is held down. When released, the button events stop. This is an async/non-blocking window.
sg.OneLineProgressMeter('One Line Meter Example', i+1, 1000, 'key')
-----
## Button Graphics (Media Player)
Buttons can have PNG of GIF images on them. This Media Player recipe requires 4 images in order to function correctly. The background is set to the same color as the button background so that they blend together.
# If a button was pressed, display it on the GUI by updating the text element
if event:
window.FindElement('output').Update(event)
----
## Script Launcher - Persistent Window
This Window doesn't close after button clicks. To achieve this the buttons are specified as `sg.ReadButton` instead of `sg.Button`. The exception to this is the EXIT button. Clicking it will close the window. This program will run commands and display the output in the scrollable window.
window = sg.Window('Machine Learning Front End', font=("Helvetica", 12)).Layout(layout)
event, values = window.Read()
-------
## Custom Progress Meter / Progress Bar
Perhaps you don't want all the statistics that the EasyProgressMeter provides and want to create your own progress bar. Use this recipe to do just that.
# check to see if the cancel button was clicked and exit loop if clicked
event, values = window.ReadNonBlocking()
if event == 'Cancel' or values == None:
break
# update bar with loop value +1 so that bar eventually reaches the maximum
window.FindElement('progbar').UpdateBar(i + 1)
# done with loop... need to destroy the window as it's still open
window.CloseNonBlocking()
----
## The One-Line GUI
For those of you into super-compact code, a complete customized GUI can be specified, shown, and received the results using a single line of Python code.
A Column is required when you have a tall element to the left of smaller elements.
In this example, there is a Listbox on the left that is 3 rows high. To the right of it are 3 single rows of text and input. These 3 rows are in a Column Element.
To make it easier to see the Column in the window, the Column background has been shaded blue. The code is wordier than normal due to the blue shading. Each element in the column needs to have the color set to match blue background.
The Canvas Element is one of the few tkinter objects that are directly accessible. The tkinter Canvas widget itself can be retrieved from a Canvas Element like this:
can = sg.Canvas(size=(100,100))
tkcanvas = can.TKCanvas
tkcanvas.create_oval(50, 50, 100, 100)
While it's fun to scribble on a Canvas Widget, try Graph Element makes it a downright pleasant experience. You do not have to worry about the tkinter coordinate system and can instead work in your own coordinate system.
## Graph Element - drawing circle, rectangle, etc, objects
Just like you can draw on a tkinter widget, you can also draw on a Graph Element. Graph Elements are easier on the programmer as you get to work in your own coordinate system.
## Keypad Touchscreen Entry - Input Element Update
This Recipe implements a Raspberry Pi touchscreen based keypad entry. As the digits are entered using the buttons, the Input Element above it is updated with the input digits.
There are a number of features used in this Recipe including:
# Loop forever reading the window's values, updating the Input field
keys_entered = ''
while True:
event, values = window.Read() # read the window
if event is None: # if the X button clicked, just exit
break
if event == 'Clear': # clear keys if clear button
keys_entered = ''
elif event in '1234567890':
keys_entered = values['input'] # get what's been entered so far
keys_entered += event # add the new digit
elif event == 'Submit':
keys_entered = values['input']
window.FindElement('out').Update(keys_entered) # output the final string
window.FindElement('input').Update(keys_entered) # change the window to reflect current key string
## Animated Matplotlib Graph
Use the Canvas Element to create an animated graph. The code is a bit tricky to follow, but if you know Matplotlib then this recipe shouldn't be too difficult to copy and modify.
Saw this example layout written in tkinter and liked it so much I duplicated the interface. It's "tight", clean, and has a nice dark look and feel.
This Recipe also contains code that implements the button interactions so that you'll have a template to build from.
In other GUI frameworks this program would be most likely "event driven" with callback functions being used to communicate button events. The "event loop" would be handled by the GUI engine. If code already existed that used a call-back mechanism, the loop in the example code below could simply call these callback functions directly based on the button text it receives in the window.Read call.
Use the upper half to generate your hash code. Then paste it into the code in the lower half. Copy and paste lower 1/2 into your code to get password protection for your script without putting the password into your source code.
Create a secure login for your scripts without having to include your password in the program. Create an SHA1 hash code for your password using the GUI. Paste into variable in final program
1. Choose a password
2. Generate a hash code for your chosen password by running program and entering 'gui' as the password
3. Type password into the GUI
4. Copy and paste hash code Window GUI into variable named login_password_hash
if password == 'gui': # Remove when pasting into your program
HashGeneratorGUI() # Remove when pasting into your program
exit(69) # Remove when pasting into your program
if PasswordMatches(password, login_password_hash):
print('Login SUCCESSFUL')
else:
print('Login FAILED!!')
## Desktop Floating Toolbar
#### Hiding your windows commmand window
For this and the Time & CPU Widgets you may wish to consider using a tool or technique that will hide your Windows Command Prompt window. I recommend the techniques found on this site:
At the moment I'm using the technique that involves wscript and a script named RunNHide.vbs. They are working beautifully. I'm using a hotkey program and launch by using this script with the command "python.exe insert_program_here.py". I guess the next widget should be one that shows all the programs launched this way so you can kill any bad ones. If you don't properly catch the exit button on your window then your while loop is going to keep on working while your window is no longer there so be careful in your code to always have exit explicitly handled.
### Floating toolbar
This is a cool one! (Sorry about the code pastes... I'm working in it)
Impress your friends at what a tool-wizard you are by popping a custom toolbar that you keep in the corner of your screen. It stays on top of all your other windows.
Demo_Toolbar - A floating toolbar with quick launcher One cool PySimpleGUI demo. Shows borderless windows, grab_anywhere, tight button layout
You can setup a specific program to launch when a button is clicked, or use the Combobox to select a .py file found in the root folder, and run that file. """
ROOT_PATH = './'
def Launcher():
def print(line):
window.FindElement('output').Update(line)
sg.ChangeLookAndFeel('Dark')
namesonly = [f for f in os.listdir(ROOT_PATH) if f.endswith('.py') ]
This is a little widget you can leave running on your desktop. Will hopefully see more of these for things like checking email, checking server pings, displaying system information, dashboards, etc
.
Much of the code is handling the button states in a fancy way. It could be much simpler if you don't change the button text based on state.
Timer Desktop Widget Creates a floating timer that is always on top of other windows You move it by grabbing anywhere on the window Good example of how to do a non-blocking, polling program using PySimpleGUI Can be used to poll hardware when running on a Pi NOTE - you will get a warning message printed when you exit using exit button. It will look something like: invalid command name \"1616802625480StopMove\"
Like the Timer widget above, this script can be kept running. You will need the package psutil installed in order to run this Recipe.
The spinner changes the number of seconds between reads. Note that you will get an error message printed when exiting because the window does not have have a titlebar. It's a known problem.
Menus are nothing more than buttons that live in a menu-bar. When you click on a menu item, you get back a "button" with that menu item's text, just as you would had that text been on a button.
Menu's are defined separately from the GUI window. To add one to your window, simply insert sg.Menu(menu_layout). The menu definition is a list of menu choices and submenus. They are a list of lists. Copy the Recipe and play with it. You'll eventually get when you're looking for.
If you double click the dashed line at the top of the list of choices, that menu will tear off and become a floating toolbar. How cool!
# ------ Loop & Process button menu choices ------ #
while True:
event, values = window.Read()
if event == None or event == 'Exit':
break
print('Button = ', event)
# ------ Process menu choices ------ #
if event == 'About...':
sg.Popup('About this program', 'Version 1.0', 'PySimpleGUI rocks...')
elif event == 'Open':
filename = sg.PopupGetFile('file to open', no_window=True)
print(filename)
## Graphing with Graph Element
Use the Graph Element to draw points, lines, circles, rectangles using ***your*** coordinate systems rather than the underlying graphics coordinates.
In this example we're defining our graph to be from -100, -100 to +100,+100. That means that zero is in the middle of the drawing. You define this graph description in your call to Graph.
Tabs bring not only an extra level of sophistication to your window layout, they give you extra room to add more elements. Tabs are one of the 3 container Elements, Elements that hold or contain other Elements. The other two are the Column and Frame Elements.
window = sg.Window('My window with tabs', default_element_size=(12,1)).Layout(layout)
while True:
event, values = window.Read()
print(event,values)
if event is None: # always, always give a way out!
break
```
## Creating a Windows .EXE File
It's possible to create a single .EXE file that can be distributed to Windows users. There is no requirement to install the Python interpreter on the PC you wish to run it on. Everything it needs is in the one EXE file, assuming you're running a somewhat up to date version of Windows.
Installation of the packages, you'll need to install PySimpleGUI and PyInstaller (you need to install only once)
pip install PySimpleGUI
pip install PyInstaller
To create your EXE file from your program that uses PySimpleGUI, `my_program.py`, enter this command in your Windows command prompt:
pyinstaller -wF my_program.py
You will be left with a single file, `my_program.exe`, located in a folder named `dist` under the folder where you executed the `pyinstaller` command.
That's all... Run your `my_program.exe` file on the Windows machine of your choosing.
> "It's just that easy."
>
(famous last words that screw up just about anything being referenced)
Your EXE file should run without creating a "shell window". Only the GUI window should show up on your taskbar.