I was frustrated by having to deal with the dos prompt when I had a powerful Windows machine right in front of me. Why is it SO difficult to do even the simplest of input/output to a window in Python??
With a simple GUI, it becomes practical to "associate" .py files with the python interpreter on Windows. Double click a py file and up pops a GUI window, a more pleasant experience than opening a dos Window and typing a command line.
Python itself doesn't have a simple GUI solution... nor did the *many* GUI packages I tried. Most tried to do TOO MUCH, making it impossible for users to get started quickly. Others were just plain broken, requiring multiple files or other packages that were missing.
The PySimpleGUI solution is focused on the ***developer***. How can the desired result be achieved in as little and as simple code as possible? This was the mantra used to create PySimpleGUI.
You can add a GUI to your command line with a single line of code. With 3 or 4 lines of code you can add a fully customized GUI.
The customization power comes from the form/dialog box builder that enables users to experience all of the normal GUI widgets without having to write a lot of code.
Simply download the file - PySimpleGUI.py and import it into your code
### Prerequisites
Python 3
tkinter
Should run on all Python platforms that have tkinter running on them. Has been thoroughly tested on Windows. While not tested elsewhere, should work on Linux, Mac, Pi, etc.
### Using
To us in your code, simply import....
`import PySimpleGUI as SG`
Then use either "high level" API calls or build your own forms.
The "High Level" API calls that *output* values take a variable number of arguments so that they match a "print" statement as much as possible. The idea is to make it simple for the programmer to output as many items as desired and in any format. The user need not convert the variables to be output into the strings. The PySimpleGUI functions do that for the user.
SG.MsgBox('Variable number of parameters example', my_variable, second_variable, "etc")
This feature of the Python language is utilized ***heavily*** as a method of customizing forms and part of forms. Rather than requiring the programmer to specify every possible option for a widget, instead only the options the caller wants to override are specified.
Here is the function definition for the MsgBox function. The details aren't important. What is important is seeing that there is a long list of potential tweaks that a caller can make. However, they don't have to be specified on each and every call.
The classic "input a value, print result" example.
Often command line programs simply take some value as input on the command line, do something with it and then display the results. Moving from the command line to a GUI is very simple.
This code prompts user to input a line of text and then displays that text in a messages box:
In addition to MsgBox, you'll find a several API calls that are shortcuts to common messages boxes. You can achieve similar results by calling MsgBox with the correct parameters.
Take a moment to look at that last one. It's such a simple API call and yet the result is awesome. Rather than seeing text scrolling past on your display, you can capture that text and present it in a scrolled interface. It's handy enough of an API call that it can also be called using the name `sprint` which is easier to remember than `ScrollectTextBox`.
There are 3 very basic user input high-level function calls. It's expected that for most applications, a custom input form will be created. If you need only 1 value, then perhaps one of these high level functions will work.
This is the FUN part of the programming of this GUI. In order to really get the most out of the API, you should be using an IDE that supports auto complete or will show you the definition of the function. This will make customizing go smoother.
It's both not enjoyable nor helpful to immediately jump into tweaking each and every little thing available to you. Let's start with a basic Browse for a file and do something with it.
It's important to use the "with" context manager. PySimpleGUI uses `tkinter`. `tkinter` is very picky about who releases objects and when. The `with` takes care of disposing of everything properly for you.
PySimpleGUI's goal with the API is to be easy on the programmer. An attempt was made to make the program's code visually match the window on the screen. The way this is done is that a GUI is broken up into "Rows". Then each row is broke up into "Elements" or "Widgets". Each element is specified by names such as Text, Button, Checkbox, etc.
Some elements are shortcuts, again meant to make it easy on the programmer. Rather than writing a `Button`, with name = "Submit", etc, the caller simply writes `Submit`.
form_rows = [[SG.Text('SHA-1 and SHA-256 Hashes for the file')],
The next few rows of code lay out the rows of elements in the window to be displayed. The variable `form_rows` holds our entire GUI window. The first row of this form has a Text element. These simply display text on the form.
[SG.InputText(), SG.FileBrowse()],
Now we're on the second row of the form. On this row there are 2 elements. The first is an `Input` field. It's a place the user can enter `strings`. The second element is a `File Browse Button`. A file or folder browse button will always fill in the text field to it's left unless otherwise specified. In this example, the File Browse Button will interact with the `InputText` field to its left.
[SG.Submit(), SG.Cancel()]]
The last line of the `form_rows` variable assignment contains a Submit and a Cancel Button. These are buttons that will cause a form to return its valueso the caller.
This is the code that **displays** the form, collects the information and returns the data collected. In this example we have a button return code and only 1 input field.
MsgBox('Results', 'You clicked {}'.format(button),'The values returned from form', values , Font = ("Helvetica", 15))
This is a somewhat complex form with quite a bit of custom sizing to make things line up well. This is code you only have to write once. When looking at the code, remember that what you're seeing is a list of lists. Each row contains a list of Graphical Elements that are used to create the form.
One important aspect of this example is the return codes:
(button, (values)) = form.LayoutAndShow(layout)
The value for `button` will be the text that is displayed on the button element when it was created. If the user closed the form using something other than a button, then `button` will be `None`.
You can see in the MsgBox that the values returned are a list. Each input field in the form generates one item in the return values list. All input fields return a `string` except for Check Boxes. These return `bool`.
# Building Custom Forms
You will find it much easier to write code using PySimpleGUI is you use features that show you documentation about the API call you are making. In PyCharm 2 commands are helpful.
> Control-Q (when cursor is on function name) brings up a box with the
> function definition
> Control-P (when cursor inside function call "()")
> shows a list of parameters and their default values
## Synchronous Forms
The most common use of PySimpleGUI is to display and collect information from the user. The most straightforward way to do this is using a "blocking" GUI call. Execution is "blocked" while waiting for the user to close the GUI form/dialog box.
You've already seen a number of examples above that use blocking forms. Anytime you see a context manager used (see the `with` statement) it's most likely a blocking form. You can examine the show calls to be sure. If the form is a non-blocking form, it must indicate that in the call to `form.show`.
NON-BLOCKING form call:
form.Show(NonBlocking=True)
### Beginning a Form
The first step is to create the form object using the desired form customization.
with FlexForm('Everything bagel', AutoSizeText=True, DefaultElementSize=(30,1)) as form:
Let's go through the options available when creating a form.
Note several variables that deal with "size". Element sizes are measured in characters. A Text Element with a size of 20,1 has a size of 20 characters wide by 1 character tall.
Sizes can be set at the element level, or in this case, the size variables apply to all elements in the form. Setting `Size=(20,1)` in the form creation call will set all elements in the form to that size.
In addition to `size` there is a `scale` option. Scale will take the Element's size and scale it up or down depending on the scale value. `scale=(1,1)` doesn't change the Element's size. `scale=(2,1)` will set the Element's size to be twice as wide as the size setting.
The most basic element is the Text element. It simply displays text. Many of the 'options' that can be set for a Text element are shared by other elements. Size, Scale are a couple that you will see in every element.
Text(Text,
Scale=(None, None),
Size=(None, None),
AutoSizeText=None,
Font=None,
TextColor=None)
Some commonly used elements have 'shorthand' versions of the functions to make the code more compact. The functions `T` and `Txt` are the same as calling `Text`.
**Fonts** in PySimpleGUI are always in this format:
(font_name, point_size)
The default font setting is
("Helvetica", 10)
**Colos** in PySimpleGUI are always in this format:
(foreground, background)
The values foreground and background can be the color names or the hex value formatted as a string:
"#RRGGBB"
#### Multiline Text Element
layout = [[SG.Multiline('This is what a Multi-line Text Element looks like', Size=(45,5))]]
This Element doubles as both an input and output Element. The `DefaultText` optional parameter is used to indicate what to output to the window.
Multiline(DefaultText='',
EnterSubmits = False,
Scale=(None, None),
Size=(None, None),
AutoSizeText=None)
> DefaultText - Text to display in the text box
>EnterSubmits - Bool. If True, pressing Enter key submits form
>Scale - Element's scale
>Size - Element's size
>AutoSizeText - Bool. Change width to match size of text
### Input Elements
These make up the majority of the form definition. Optional variables at the Element level override the Form level values (e.g. `Size` is specified in the Element).