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 characters. Replace the import statement:
If you like this Cookbook, then you'll LOVE the 170+ sample programs that are just like these. You'll find them in the GitHub at http://www.PySimpleGUI.com. These Recipes are simply several of those programs displayed in document format.
All of your PySimpleGUI programs will utilize one of these 2 design patterns depending on the type of window you're implementing. The two types of windows are:
1. One-shot window
2. Persistent window
The one-shot window is one that pops up, collects some data, and then disappears. It is more or less a 'form'.
The "Persistent" window is one that sticks around. With these programs, you loop, reading and processing "events" such as button clicks.
This will be the most common pattern you'll follow if you are not using an "event loop" (not reading the window multiple times). The window is read and then closes.
Because no "keys" were specified in the window layout, the return values will be a list of values. If a key is present, then the values are a dictionary. See the main readme document or further down in this document for more on these 2 ways of reading window values.
## Pattern 2 A - Persistent window (multiple reads using an event loop)
Some of the more advanced programs operate with the window remaining visible on the screen. Input values are collected, but rather than closing the window, it is kept visible acting as a way to both output information to the user and gather input data.
This code will present a window and will print values until the user clicks the exit button or closes window using an X.
## Pattern 2 B - Persistent window (multiple reads using an event loop + updates data in window)
This is a slightly more complex, but maybe more realistic version that reads input from the user and displays that input as text in the window. Your program is likely to be doing both of those activities so this will give you a big jump-start.
Do not worry yet what all of these statements mean. Just copy it so you can begin to play with it, make some changes. Experiment to see how thing work.
A final note... the parameter `do_not_clear` in the input call determines the action of the input field after a button event. If this value is True, the input value remains visible following button clicks. If False, then the input field is CLEARED of whatever was input. If you are building a "Form" type of window with data entry, you likely want False. The default setting is True so they are not cleared. Some older programs may explicitly set this parameter to True.
# 1 Shot - Simple Data Entry - Return Values - Auto Numbered
An Element's key will be automatically numbered, starting at 0, if you do not use the `key` parameter when creating an element and it's an element that will return values to you via the `Window.Read()` call.
This example has no keys specified. The 3 input fields will have keys 0, 1, 2. Keys like this make the return values look like a list rather than a dictionary. Your first input element will be accessed as `values[0]`, just like a list would look.
A simple GUI with default values in input elements, and uses user defined keys. You will normally use keys like in this example. If you use autonumbering, then if you add an element between other elements, then your numbering will shift and you'll have to modify your code quite a bit. By naming them yourself, you can use the key to store data and be more descriptive.
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. If you want command line, you can use it. If you don't specify, then the GUI will fire up.
### The "Single Line GUI" version
Here's the "single line GUI" version of a front-end
raise SystemExit("Cancelling: no filename supplied")
```
### The More "Typical Version"
That's showing off a bit just to crunch things down to a single line of GUI code.
It's unusual to use the `CloseButton` Element. Typically you use `Button`. Normally you would not chain together so many calls. Instead you would create the `Window` and put into `window` variable. Then `Read` the window and finally `window.Close()`
Using the more "traditional" style PySimpleGUI code:
```python
import PySimpleGUI as sg
import sys
if len(sys.argv) == 1:
layout = [[sg.Text('Document to open')],
[sg.In(), sg.FileBrowse()],
[sg.Open(), sg.Cancel()]]
window = sg.Window('My Script', layout)
event, values = window.Read()
window.Close()
fname = values[0]
print(event, values)
else:
fname = sys.argv[1]
if not fname:
sg.Popup("Cancel", "No filename supplied")
raise SystemExit("Cancelling: no filename supplied")
## Nearly All Elements with Color Theme, Menus, (The Everything Bagel)
Example of nearly all of the Elements in a single window. Uses a customized color scheme, lots of Elements, default values, Columns, Frames with colored text, tooltips, file browsing. There are at least 13 different Elements used.
Before scrolling down to the code, guess how many lines of Python code were required to create this custom layout window.
[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))],
That's what the window definition, creation, display and get values ultimately ended up being when you remove the blank lines above. Try displaying 13 seperate "GUI Widgets" in any of the GUI frameworks. There's $20 waiting for the person that can code up the same window in under 35 lines of Python code using tkinter, WxPython, or Qt
An async Window that has a event loop, and updates a text element at a periodic interval. In this case, we're outputting the time elapsed into the window.
Use this design pattern for projects that need to poll or output something on a regular basis. In this case, we're indicating we want a `timeout=10` on our `window.Read` call. This will cause the `Read` call to return a "timeout key" as the event when a timeout has happened without some GUI thing happening first (like the user clicking a button). The timeout key is `PySimpleGUI.TIMEOUT_KEY` usually written as `sg.TIMEOUT_KEY` in normal PySimpleGUI code.
Use caution when using windows with a timeout. You should **rarely** need to use a `timeout=0`, non-blocking call, so try not to abuse this design pattern. Honest, you shouldn't do it unless you're a realtime application and know what you're doing. Hint - if you have <1yearprogrammingexperienceandyou'reusing`timeout=0`,you'redoingsomethingwrong.
A note about timers... this is not a good design for a stopwatch as it can very easily drift. This would never pass for a good solution in a bit of commercial code. For better accuracy always get the actual time from a reputable source, like the operating system. Use that as what you use to measure and display the time.
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.
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.
This Window doesn't close after button clicks. To achieve this the buttons are specified as `sg.Button` 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.
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.
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.
This recipe is a design pattern for multiple windows where the first window is not active while the second window is showing. The first window is hidden to discourage continued interaction.
```Python
"""
PySimpleGUI The Complete Course Lesson 7 - Multiple Windows"""
import PySimpleGUI as sg
# Design pattern 1 - First window does not remain active
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:
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:
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
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. """
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 SimpleGUI Can be used to poll hardware when running on a Pi
While the timer ticks are being generated by PySimpleGUI's "timeout" mechanism, the actual value
of the timer that is displayed comes from the system timer, time.time(). This guarantees an
accurate time value is displayed regardless of the accuracy of the PySimpleGUI timer tick. If
this design were not used, then the time value displayed would slowly drift by the amount of time
it takes to execute the PySimpleGUI read and update calls (not good!)
NOTE - you will get a warning message printed when you exit using exit button.
It will look something like: invalid command name \"1616802625480StopMove\"
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! To enable this feature, set the parameter `tearoff=True` in your call to `sg.Menu()`
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.
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)