Quick and easy with PySimpleGUI

Simple Is Good

© Lead Image © Andrey Burmakin, 123RF.com

© Lead Image © Andrey Burmakin, 123RF.com

Author(s):

Use the same code for your Python GUI and web apps.

The PySimpleGUI project has two main goals: a simpler method for creating graphical user interfaces (GUIs), and common code for Tkinter, QT, Wx, and web graphics. Although I feel comfortable doing my own Python Tkinter and web interfaces, having common code for both local GUI and web apps could be extremely useful, especially for Raspberry Pi projects. In this article, I introduce PySimpleGUI and create both a local GUI and a web interface to control a Raspberry Pi rover, all in less than 60 lines of code.

Getting Started

The Python PySimpleGUI [1] project has a number of "ports" or versions. The main full-featured version is for Tkinter-based graphics. The versions for Qt, Wx, and web graphics are still in development, so some testing will be required if you are hoping for full code compatibility between the different libraries.

Although you probably won't encounter a lot of cases in which you would want to flip between Qt, Wx, and Tkinter graphic engines, the possibility exists. Figure 1 shows examples of the same code applied to the different graphic libraries.

Figure 1: PySimpleGUI uses the graphic libraries for (top to bottom) Tkinter, Qt, Wx, and a web app.

To install the default version of PySimpleGUI for Tkinter enter:

pip install pysimpleGUI

PySimpleGUI has a wide range of graphic widgets or elements. Graphic presentations are built by creating a layout variable, and elements are placed in separate rows defined by enclosing square brackets. A row can have a single element or multiple elements. Figure 2 is a graphic GUI example with three rows.

Figure 2: PySimpleGUI layout example.

A Button Interface

The rover project I create in this article uses a five-row layout (Listing 1; Figure 3). The first row contains feedback text, and rows 2-5 contain buttons.

Listing 1

PySimpleGUI Button

01 # Create a simple graphic interface
02 #
03 import PySimpleGUI as sg
04
05 layout = [ [sg.Text("the feedback" , key="feedback")],
06            [sg.Button("FORWARD")],
07            [sg.Button("LEFT"),sg.Button("RIGHT")],
08            [sg.Button("STOP")],
09            [sg.Button("QUIT")]
10           ]
11 # Create the Window
12 window = sg.Window('My First App', layout)
13 # Event Loop to process "events"
14 while True:
15     event, values = window.read()
16     window['feedback'].Update(event) # show the button in the feedback text
17     print(event,values)
18     if event in (None, 'QUIT'):
19         break
20 window.close()
Figure 3: PySimpleGUI button example.

The PySimpleGUI sg.window() method displays a window with the title and a layout definition (line 12). The window.read() method returns events and values that have changed (line 15). The feedback text element (line 5) is given the key name feedback, which is used by the Update method to indicate which button is pressed (line 16).

Standalone Web Apps

The PySimpleGUIWeb library is excellent for creating a lightweight standalone web interface. The real beauty in PySimpleGUIWeb is that no HTML, style sheets, Ajax, or JavaScript code is required. PySimpleGUIWeb is ideal for small, single-user web interfaces, and it supports features like a tabbed interface, tables, and graphics; however, it would not be a good fit if you need a multipage-multiuser web environment.

To install PySimpleGUIWeb enter:

pip install remi
pip install pysimpleGUIweb

If I use my earlier button example, but this time use the PySimpleGUIWeb library, the code is identical, except for some added window options (Figure 4). If you are working locally on a Raspberry Pi, you can use the default sg.window settings; however, if you want to work remotely, you need to define a web server address (web_ip) and port (web_port) and to disable the auto launching of the a web browser (web_start_browser = False).

Figure 4: PySimpleGUIWeb button example.

Formatting Display Elements

The next step is to adjust the fonts, colors, and size properties of the graphic elements. With just three lines you can change the FORWARD button to 32 characters wide and three lines high with added color and a larger font:

[sg.Button("FORWARD", size=(32,3),
  font="Ariel 32",
  button_color=('white','green'))]

To make the rover control interface more usable, you can enlarge and add color to all the control buttons (Figure 5).

Figure 5: PySimpleGUI rover GUI.

Raspberry Pi Rover

For my rover, I used a low-cost Arduino car chassis (~$15) and a portable phone charger to power the Raspberry Pi. Duct or painters tape works well to secure the Pi and charger to the car chassis.

Connecting motors directly to the Raspberry Pi GPIO pins is not recommended because their power requirements could damage your Raspberry Pi. If you're on a budget, you can create your own motor protection circuit with an L298N dual H-bridge chip (~$2); otherwise, you can find a variety of Pi motor or relay tops. For this project, I used a Pimoroni Explorer HAT Pro [2] (~$22).

For the final code (Listing 2), I added a command-line option (lines 6-10) that allows either a local Tkinter interface or a web interface. The program default is a Tkinter GUI; however, if any command-line text is entered, the PySimpleGUIWeb interface is used.

Listing 2

PySimpleGUI/Web Rover

01 # SGui_rover.py - use PySimpleGUI/Web to control a Pi Rover Pi
02 #
03
04 import sys
05 # Pass any command line argument for Web use
06 if len(sys.argv) > 1: # if there is use the Web Interface
07     import PySimpleGUIWeb as sg
08     mode = "web"
09 else: # default uses the tkinter GUI
10     import PySimpleGUI as sg
11
12 import RPi.GPIO as gpio
13 gpio.setmode(gpio.BOARD)
14 # Define the motor pins to match your setup
15 motor1pin = 38 # left motor
16 motor2pin = 37 # right motor
17 gpio.setup(motor1pin, gpio.OUT)
18 gpio.setup(motor2pin, gpio.OUT)
19
20 # Send Action to Control Rover
21 def rover(action):
22 if action == "FORWARD":
23     gpio.output(motor1pin, gpio.HIGH)
24     gpio.output(motor2pin, gpio.HIGH)
25 if action == "LEFT":
26     gpio.output(motor1pin, gpio.HIGH)
27     gpio.output(motor2pin, gpio.LOW)
28 if action == "RIGHT":
29     gpio.output(motor1pin, gpio.LOW)
30     gpio.output(motor2pin, gpio.HIGH)
31 if action == "STOP":
32     gpio.output(motor1pin, gpio.LOW)
33     gpio.output(motor2pin, gpio.LOW)
34
35 # All the stuff inside your window.
36 myfont = "Ariel 32"
37 layout = [ [sg.Text(" ",size=(20,1) , key="feedback")],
38 [sg.Button("FORWARD", size=(32,3), font=myfont, button_color=('white','green'))],
39 [sg.Button("LEFT", size=(15,3), font=myfont),sg.Button("RIGHT", size=(15,3), font=myfont)],
40 [sg.Button("STOP", size=(32,3), font=myfont, button_color=('white','red'))],
41 [sg.Button("QUIT")]
42 ]
43 # Create the Window
44 if mode == "web":
45     window = sg.Window('PySimpleGUI Rover Control', layout,
46         web_ip='192.168.0.106', web_port = 8888, web_start_browser=False)
47 else:
48     window = sg.Window('PySimpleGUI Rover Control', layout )
49
50 # Event Loop to process "events" and pass them to the rover function
51 while True:
52     event, values = window.read()
53     print(event,values)
54     if event in (None, 'QUIT'): # if user closes window or clicks cancel
55         break
56     window['feedback'].Update(event) # show the button in the feedback text
57     rover(event)
58
59 window.close() # exit cleanly

The forward left and right motor pins are defined on lines 15 and 16. If you are using a Pi motor HAT or an L298N circuit, you can also define backward left and right motor pins. (Direct-wiring the Pi pins or using a relay top only supports one direction for the motors.)

A rover function (lines 21-33) controls the motors according to button events. Figure 6 shows the Raspberry Pi rover with the web interface.

Figure 6: Raspberry Pi rover with PySimpleGUIWeb.

Summary

I was very happy with the performance and features offered by the PySimpleGUI library, and I found that the Pi rover project was a simple way to get started. For small Internet of Things (IoT) projects, you can use PySimpleGUI and PySimpleGUIWeb to create dashboard interfaces with bar and real-time charts.

Infos

  1. PySimpleGUI docs: https://pysimpleGUI.readthedocs.io/
  2. Pimoroni Explorer HAT Pro: https://www.adafruit.com/product/2427

The Author

You can investigate more neat projects by Pete Metcalfe and his daughters at https://funprojects.blog.