Skip to content

Creating a Simple GUI in Python Effortlessly

[

PySimpleGUI: The Simple Way to Create a GUI With Python

Creating a simple graphical user interface (GUI) that works across multiple platforms can be complicated. But it doesn’t have to be that way. You can use Python and the PySimpleGUI package to create nice-looking user interfaces that you and your users will enjoy! PySimpleGUI is a new Python GUI library that has been gaining a lot of interest recently.

In this tutorial, you’ll learn how to:

  • Install the PySimpleGUI package
  • Create basic user interface elements with PySimpleGUI
  • Create applications, such as a PySimpleGUI image viewer
  • Integrate PySimpleGUI with Matplotlib
  • Use computer vision in PySimpleGUI
  • Package your PySimpleGUI application for Windows

Getting Started With PySimpleGUI

PySimpleGUI was launched in 2018, so it’s a relatively new package compared with the likes of wxPython or PyQt.

PySimpleGUI has four ports:

  1. Tkinter
  2. PyQt
  3. wxPython
  4. Remi

PySimpleGUI wraps portions of each of these other packages and makes them easier to use. However, each of the ports has to be installed separately.

PySimpleGUI wraps the entirety of Tkinter, which comes with Python. PySimpleGUI has wrapped most of PySide2, but only a small portion of wxPython. When you install PySimpleGUI, you get the Tkinter variant by default. For more information about Tkinter, check out Python GUI Programming With Tkinter.

Depending on which variant of PySimpleGUI you use, applications that you create with PySimpleGUI may not look native to their platform. But don’t let this stop you from giving PySimpleGUI a try. PySimpleGUI is still quite powerful and can get most things done with a little work.

Installing PySimpleGUI

Installing PySimpleGUI is easy if you use pip. For the purposes of this tutorial, you’ll learn how to install the regular PySimpleGUI port, which is the Tkinter variant.

Here’s how to do it:

Terminal window
$ python -m pip install pysimplegui

This will install PySimpleGUI to whatever your system Python is set to. You can also install PySimpleGUI to a Python virtual environment. If you’re unfamiliar with Python virtual environments, then you should read Python Virtual Environments: A Primer.

If you prefer to try the PyQt variant, then you can use pip install PySimpleGUIQt instead. Now that you have PySimpleGUI installed, it’s time to find out how to use it!

Creating Basic UI Elements in PySimpleGUI

Let’s start by creating some basic user interface (UI) elements with PySimpleGUI. With PySimpleGUI, you can create buttons, input fields, checkboxes, and more with just a few lines of code.

To create a window with PySimpleGUI, you’ll need to import the library and then call the sg.Window function. The sg module comes from PySimpleGUI.

import PySimpleGUI as sg
# Create a window
window = sg.Window("My First GUI", layout)
# Read events from the window
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
# Close the window
window.close()

Inside the window, you can add various UI elements using the sg.Element class. Here are some common UI elements you can create:

  • Buttons: sg.Button("Click me!", size=(10, 2))
  • Input fields: sg.Input(size=(20, 1))
  • Checkboxes: sg.Checkbox("Check me!")
  • Dropdown menus: sg.Combo(["Option 1", "Option 2", "Option 3"], default_value="Option 1")

You can add these UI elements to your window by appending them to a layout list. The layout is a list of lists that specifies the arrangement of UI elements in the window.

Here’s an example of a simple window with a button and an input field:

import PySimpleGUI as sg
# Define the layout of the window
layout = [
[sg.Text("Enter your name:"), sg.Input(size=(20, 1))],
[sg.Button("Submit")]
]
# Create a window
window = sg.Window("My First GUI", layout)
# Read events from the window
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
if event == "Submit":
name = values[0]
sg.popup(f"Hello, {name}!")
# Close the window
window.close()

This code creates a window with a label and an input field for the user to enter their name. When the submit button is clicked, a popup message is displayed with the entered name.

Creating Simple Applications

Now that you know how to create basic UI elements in PySimpleGUI, let’s move on to creating simple applications. You can use PySimpleGUI to build applications for a variety of purposes, such as image viewers or data analysis tools.

Here’s an example of a simple PySimpleGUI application that displays images:

import PySimpleGUI as sg
import cv2
# Define the layout of the window
layout = [
[sg.Text("Select an image:")],
[sg.Input(key="-FILENAME-"), sg.FileBrowse()],
[sg.Button("Load")]
]
# Create a window
window = sg.Window("Image Viewer", layout)
# Read events from the window
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
if event == "Load":
filename = values["-FILENAME-"]
image = cv2.imread(filename)
sg.Image(filename).update(data=cv2.imencode(".png", image)[1].tobytes())
# Close the window
window.close()

This code creates a simple image viewer that allows the user to select an image file using a file browser. When the “Load” button is clicked, the selected image is displayed in the window.

Integrating Matplotlib With PySimpleGUI

PySimpleGUI can also be integrated with other popular Python libraries, such as Matplotlib. This allows you to create interactive plots and graphs directly within your PySimpleGUI windows.

Here’s an example of how to integrate Matplotlib with PySimpleGUI:

import PySimpleGUI as sg
import matplotlib.pyplot as plt
import numpy as np
# Generate some data
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
# Create a figure and axis
fig, ax = plt.subplots()
ax.plot(x, y)
# Convert the figure to a PNG image
figure = plt.gcf()
figure.canvas.draw()
data = np.array(figure.canvas.renderer.buffer_rgba())
# Define the layout of the window
layout = [
[sg.Image(data=data)],
[sg.Button("Close")]
]
# Create a window
window = sg.Window("Matplotlib Integration", layout)
# Read events from the window
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED or event == "Close":
break
# Close the window
window.close()

This code creates a PySimpleGUI window that displays a Matplotlib plot. The plot is generated using some sample data and then converted to a PNG image. The PNG image is then displayed in the PySimpleGUI window using the sg.Image element.

Integrating OpenCV With PySimpleGUI

If you’re working with computer vision tasks, you’ll be happy to know that PySimpleGUI can also be integrated with OpenCV. This allows you to create GUIs for image processing tasks, such as object detection or facial recognition.

Here’s an example of how to integrate OpenCV with PySimpleGUI:

import PySimpleGUI as sg
import cv2
# Define the layout of the window
layout = [
[sg.Image(key="-IMAGE-")],
[sg.Button("Open"), sg.Button("Process"), sg.Button("Save")]
]
# Create a window
window = sg.Window("OpenCV Integration", layout)
# Read events from the window
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
if event == "Open":
filename = sg.popup_get_file("Select an image file")
if filename != "":
image = cv2.imread(filename)
window["-IMAGE-"].update(data=cv2.imencode(".png", image)[1].tobytes())
if event == "Process":
# Process the image here
pass
if event == "Save":
# Save the image here
pass
# Close the window
window.close()

This code creates a PySimpleGUI window that allows the user to open an image file, process the image, and save the result. The image is displayed in the window using the sg.Image element, and OpenCV is used to perform the image processing tasks.

Packaging Your PySimpleGUI Application for Windows

Once you’ve finished creating your PySimpleGUI application, you may want to package it into an executable file for distribution. One way to do this is by using the PyInstaller library, which you can install with pip:

Terminal window
$ pip install pyinstaller

Once you have PyInstaller installed, you can use it to package your PySimpleGUI application into a Windows executable with a single command:

Terminal window
$ pyinstaller --onefile your_script.py

This will create a standalone executable file your_script.exe that can be run on any Windows machine without requiring Python or any dependencies.

Conclusion

In this tutorial, you’ve learned how to use PySimpleGUI to create user-friendly graphical user interfaces (GUIs) with Python. You’ve seen how to install PySimpleGUI, create basic UI elements, build simple applications, integrate with popular libraries like Matplotlib and OpenCV, and package your PySimpleGUI application for Windows.

With the simplicity and flexibility of PySimpleGUI, you can quickly and easily create GUIs for a wide range of applications. Whether you’re building simple tools or complex data analysis applications, PySimpleGUI is a great choice for your GUI development needs.

Now go ahead and start creating your own GUIs with PySimpleGUI!