Tutorial: Creating Graphical Interfaces in Python Using PySimpleGUI

If you are a programmer or have programmed in Python, You may have noticed how simple and easy it is to create programs, but you have also noticed that one of the drawbacks that exist in Python is the creation of graphical interfaces.

We have tkinter the native module for this task, but developing them is always complicated and involves writing many lines of code.

But what would you think if I told you that there is another easier solution to create graphical interfaces and that you can even do it with a line of code?

PySimpleGUI is a module for the design and creation of graphical interfaces in Python.

It is simple, beautiful and elegant. Optimize your lines of code and speed in creating graphical interfaces for your Python projects.

How to install PySimpleGUI? You can install it from command using pip.

pip install pysimplegui

pip3 install pysimplegui

You can visit the repository at Github to clone the project directly:

First we must understand how the PySimpleGUI designer works, in PySimpleGUI the placement of graphic objects is done as rows and columns, where we introduce the objects according to the order and position that we want to be displayed.

You can easily create graphics

Let's follow the example of the following images:

In this example we see that the first element is a text label, it is followed by a text box and finally a button. Simple, no?

Now we will see how its programming is in PySimpleGUI:

What should GUI programming look like in Python? At least for beginners?

While one goal was to simplify the creation of a GUI, Another important goal was to do it in a pythonic way. Whether it achieved these goals is debatable, but it was an equal attempt.

The key to custom windows in PySimpleGUI is to view windows as ROWS of GUI elements. Each row is specified as a list of these items. Put the rows together and you have a window. This means that the GUI is defined as a series of Lists, a pythonic way of looking at things.

Let's dissect this little program

Let's agree that the window has 4 rows.

The first row only has text 'Rename files or folders

The second row has 3 elements. First the text 'Source for Folders, then a field of 'submit’, then a button browse’.

Now let's see how those 2 rows and the other two rows of Python code:

Do you see how the source code reflects the design? Just make lists for each row, then send that table to PySimpleGUI to display and get values.

And what about those return values? Most people just want to show a window, get the input values ​​and do something with them. Then, Why split the code into button callbacks, etc., when I just want to be given the input values ​​of my window?

For return values, the window is scanned from top to bottom, from left to right. Each field that is an input field will take a place in the return values.

Show CPU Load Using PySimpleGUI

In our example window, there are 2 fields, so the return values ​​of this window will be a dictionary with 2 values. Remember, if you don't specify akey when creating an item, one will be created for you. They are ints that start with 0. In this example, we have 2 input elements. They will be addressable as values [0] and values [1]

In a statement, we both show the window and read the user input. In the following line of code, the dictionary of return values ​​is divided into individual variables'folder_pathY file_path’.

Isn't this what a Python programmer looking for a GUI wants? Something easy to work with to get the values ​​and move on to the rest of the program, where the real action is taking place. Why write GUI code pages when the same layout can be achieved with PySimpleGUI in 3 The 4 lines of code? 4 lines or 40? Most would choose 4.

Return values

There are 2 return values ​​from a call to Window.read(), a event what caused the Read Yvalues a list or dictionary of values. If there are no keyed elements in the layout, it will be a list. Nevertheless, some elements, like some buttons, have a password added automatically. It is better to use keys in all its input type elements.

Return values

All window read calls return 2 values. By convention a read statement is written:

You don't have to write your readings this way. You can name your variables whatever you want. But if you want to code them in a way that other programmers using PySimpleGUI are used to, then use this statement.

Events & Events

The first parameter event describe because I know completed the reading. Events are one of these:

For all windows:

  • Button click
  • Window closed with X

For Windows that have specifically enabled them:

  • Keyboard keystroke
  • Mouse wheel up / down
  • Selected menu item
  • A changed element (slider, roulette, etc.)
  • An item in the list was clicked
  • Return key was pressed on input item
  • Waiting time waiting for event
  • The text was clicked.
  • Chosen combo box item
  • Selected table row
  • etc.
Chess Game Using PySimpleGUI

The majority Most of the time the event will be a button click or the window was closed. Other types of Element specific events happen when you configure enable_events=True when you create the Element.

Window closed event

Another convention to follow is checking closed windows with an X. This is a critically important event to catch . If you don't check this and try to use the window, your program will crash. Check for a closed window and exit your program gracefully. Your users will like you for it.

Close the windows when you're done with them, although exiting the program will also close them. tkinter may throw an error / warning sometimes if you don't close the window. For other ports, as PySimpleGUIWeb, not closing the window will potentially cause your program to continue running in the background.

To check for a closed window, use this line of code:

Putting it all together we end up with a “event loop” what looks like this:

This if statement equals:

Instead of 'Exit' use the name / key of the button you want to exit the window (Cancel, Leave, etc.)

Button click events

Default, buttons will always return a click event, or in the case of real-time buttons, a button pressed event. You don't have to do anything to enable button clicks. To disable events, disable the button using your Update method.

You can enable an additional event “Modified button” Setting enable_events=True on the Button call. These events are fired when something “write” on a button, usually because the button appears as “target” on another button.

The value of the button for a read call will be one of the 2 values:

  1. The button text: predetermined
  2. Button key: if a key is specified

If a button has a key set when it was created, that key will be returned, regardless of the text displayed on the button. If no key is set, button text is returned.

If no button was clicked, but the window came back anyway, the event value is the key that caused the event to be generated. For example, enable_events is established in a Input Element and someone writes a character in thatInput, then the event will be the key of the input box.

Ping pong game

None returned when the user clicks the X to close a window.

If your window has an event loop where it is read over and over again, remember to give your user a “out”. Must alwayscheck the value None and it is good practice to provide an Exit button of some kind. A) Yes, design patterns often look like this event loop:

Actually, the “Pythonic version” more is used in most demo and sample programs. exactly the same.

Element Events

Some elements are capable of generating events when something happens to them. For example, when a slider is moved, or the list item is clicked or the table row is clicked. These events are not enabled by default. To enable events for an Element, set the parameter enable_events=True. This is the same as the click_submits previous parameter. You will find the click_submits parameter still in function definition. You can keep using it. They are the same scenario. A 'o is used’ of the two values. In the future, click_submits will be removed, so migrate your code to useenable_events.

Name events
InputText any change
Combo item chosen
Listbox selection changed
Radio selection changed
Checkbox selection changed
Spinner new item selected
Multiline any change
Text clicked
Status Bar clicked
Graph clicked
Graph dragged
Graph drag ended (mouse up)
TabGroup tab clicked
Slider slider moved
Table row selected
Tree node selected
ButtonMenu menu item chosen
Right click menu menu item chosen

Menu bar menu item chosen for menu bar menus and button menu menus

You will receive the key for the MenuBar and ButtonMenu. Use that key to read the value in the return value dictionary. The displayed value will be the full text plus the key for the chosen menu item. Remember that you can put keys on menu items. You will get the text and the key together as you defined it in the menu definition.

Right click menu item chosen

Unlike menu bar and button menus, you will directly receive the text of the menu item and its key value. It will not do a dictionary lookup to get the value. It is the event code returned by WindowRead ().

Windows: keyboard, mouse scroll wheel

Windows is capable of returning keyboard events. These are returned as a single character or a string if it is a special key. Experiment is all I can say. Mouse scroll wheel events are also strings. Put a print on your code to see what it returns.

Timeouts

If you set a timeout parameter on your read, the TIMEOUT_KEY system will be returned. If you specified your own time-out key on the Read call, that value will be the one returned.

The variable values: return values ​​as a list

The second parameter of a read call is a list or a dictionary of the input fields in the window.

Default, return values ​​are a list of values, one entry for each input field, but for all windows, except the simplest, return values ​​will be a dictionary. This is because it is likely to use a 'key’ in your design. When it does, forces return values ​​to be a dictionary.

Each of the elements that are input elements will have a value in the list of return values. If you know for sure that the values ​​will be returned as a list, so it could be smart and unzip directly into variables.

THE, more commonly, you can unpack the return results separately. This is the preferred method because it works so much for list and dictionary return values.

Nevertheless, this method is not good when you have many input fields. If you insert a new element in your window, then you will have to shuffle your unpacks, modifying each of the statements to reference value_list[x].

The most common method is to request that its values ​​be returned as a dictionary by placing keys in the elements “important” (those from which you want to get values ​​and with which you want to interact)

The event loop / callback functions

All GUIs have one thing in common, a “event loop”. In general, the GUI framework runs the event loop for you, but sometimes you want more control and will run your own event loop. You often hear the term event loop when talking about embedded systems or on a Raspberry Pi.

With PySimpleGUI, whether your window will stay open after clicking the buttons, your code will have an event loop. If your program shows only one window “in one go”, collect the data and then have no other GUI interaction, then you don't need an event loop.

There is nothing mysterious about event loops … they are loops in which you take care … Wait … events . Events are things like button clicks, keystrokes, mouse scroll wheel up / down.

This little program has a typical PySimpleGUI event loop.

The anatomy of a PySimpleGUI event loop is as follows, ingeneral .

  • The real part of “loop” is a while True
  • “read” any input event and value the window has
  • Check if the window was closed or if the user wants to exit
  • A series of conditions and statements

It's easy to create a graphical interface in Python.

A graphical interface in a line of code?

Let's see an interface with more elements and a little more code:

In this graphical interface we place several elements as they are, text boxes, labels and buttons.
We import the libraries

We create a class called interface, and in its init we define the elements of the graphical interface:

So the execution is like this:

In the examples I have used popup’s, so that I will list the different popup’s that are available

  • Popup
  • PopupOk
  • PopupYesNo
  • PopupCancel
  • PopupOkCancel
  • PopupError
  • PopupTimed, PopupAutoClose
  • PopupNoWait, PopupNonBlocking

and they run:

Finally we show a graphical interface that contains all the graphical objects for you to carry out your tests:

If you want us to do a specific tutorial for an example, leave it in the comments.

Follow Facialix on all his social networks:

6 thoughts on “Tutorial: Creating Graphical Interfaces in Python Using PySimpleGUI”

  1. Excellent!…how would the connection of the information that this form collects with, I do not know, mysql server for example…

  2. I need help to make an interface that asks for two data name and age after age 18 Come in 70 can vote if it is more 18 You can not vote or if you are older 70 and then ask if I register ID if not you can not vote

  3. Hello, good afternoon, you could among the graphic objects make an example of a pageframe and a grid? From already thank you very much!!! This I used in visual fox!!!

  4. Traceback (most recent call last):
    File “interfaz1.py”, line 8, in
    class interfaz:
    File “interfaz1.py”, line 29, in interfaz
    event, values = self.window.Read()
    NameError: name ‘self’ is not defined

Leave a Reply

Your email address will not be published. Required fields are marked *

eighteen − 10 =