Here is how to build a GUI with FreeSimpleGUI in Python.


FreeSimpleGUI is a Python library that makes creating graphical user interfaces (GUIs) for your applications a breeze. It is a fork of PySimpleGUI which is now a paid library to use while FreeSimpleGUI is free. FreeSimpleGUI offers a simple and intuitive API, allowing you to build user-friendly interfaces without getting bogged down in complex code. This tutorial will guide you through the basics of FreeSimpleGUI, helping you create your first simple GUI application.

Installation:

The first step is to install FreeSimpleGUI using pip:

pip install FreeSimpleGUI

Basic Elements:

FreeSimpleGUI provides various pre-built elements to construct your GUI. Here are some commonly used ones:

  • Text: Displays static text on the screen.
  • Input: Allows users to enter text.
  • Button: Triggers an action when clicked.
  • Layout: Defines the arrangement of elements within the window.

Creating a Simple Window:

Let's build a basic window with a text element and a button:

import FreeSimpleGUI as sg
# Define the layout
layout = [[sg.Text("Hello, World!"), sg.Button("Click Me")]]
# Create the window
window = sg.Window("My First GUI", layout)
# Event Loop
while True:
  event, values = window.read()
  if event == sg.WIN_CLOSED:
    break
  elif event == "Click Me":
    print("Button clicked!")
window.close()

Explanation:

  1. We import FreeSimpleGUI as sg for convenience.
  2. The layout list defines the window's content. In this case, it has a row with a text element and a button.
  3. The sg.Window function creates the window with the specified title ("My First GUI") and the layout.
  4. The while True loop keeps the window open until the user closes it.
  5. window.read() pauses the program and waits for user interaction (closing the window or clicking the button). It returns a tuple containing the event name (e.g., button click, window closed) and the current values of all input elements (empty in this case).
  6. The if statements check for the event type:
    • sg.WIN_CLOSED: The user closed the window, so we break out of the loop.
    • "Click Me": The button was clicked, and we print a message to the console.
  7. Finally, window.close() closes the window after the loop exits.

Running the Script:

Save the code as a Python file (e.g., my_window.py) and run it from the terminal:

python my_window.py

This will display a window with the text "Hello, World!" and a button labeled "Click Me." Clicking the button will print "Button clicked!" to the console.

Adding Input Fields:

Let's modify the example to include an input field where users can enter their name and a button to greet them:

import FreeSimpleGUI as sg
layout = [
  [sg.Text("Enter your name:")],
  [sg.InputText(key="name")],
  [sg.Button("Greet Me")]
]
window = sg.Window("Greeting App", layout)
while True:
  event, values = window.read()
  if event == sg.WIN_CLOSED:
    break
  elif event == "Greet Me":
    name = values["name"]
    print(f"Hello, {name}!")
window.close()

Here, we've added an sg.InputText element with the key "name" to capture user input. In the event loop, we retrieve the entered name from the "values" dictionary and use it to create a personalized greeting message.

Customizing the Look and Feel:

FreeSimpleGUI allows some basic customization options for the window and elements. Here are a couple of examples:

  • Window Size: Pass a tuple to the size argument of sg.Window to set the width and height in pixels (e.g., sg.Window("Window", layout, size=(600, 400))).
  • Font Size: Use the font argument within element creation functions to set the font and size (e.g., sg.Text("Text", font=("Arial", 12))).



Output

Output from the first example:

Output from the second example:



Explanation

  1. We import FreeSimpleGUI as sg for convenience.
  2. The layout list defines the window's content. In this case, it has a row with a text element and a button.
  3. The sg.Window function creates the window with the specified title ("My First GUI") and the layout.
  4. The while True loop keeps the window open until the user closes it.
  5. window.read() pauses the program and waits for user interaction (closing the window or clicking the button). It returns a tuple containing the event name (e.g., button click, window closed) and the current values of all input elements (empty in this case).
  6. The if statements check for the event type:
    • sg.WIN_CLOSED: The user closed the window, so we break out of the loop.
    • "Click Me": The button was clicked, and we print a message to the console.
  7. Finally, window.close() closes the window after the loop exits.



Related HowTos
Delete a directory
Delete a file
Create matplotlib graphs
Rename a file
Get today's date and convert to string
Create a text file and write text on it
Read a text file with Python
Scrape a Wikipedia page
Install dependencies
Flush the output of the print function
Prettyprint a JSON file
Create a dictionary with list comprehension
Select multiple columns in a Pandas dataframe
Profile a script
Reverse a string
Convert two lists into a dictionary
Convert an integer into a string
Generate random strings with upper case letters and digits
Extract extension from filename
Print to stderr in Python
Generate random integers between 0 and 9
Use a pythonic way to create a long multi-line string
Measure elapsed time in Python
Install specific package versions with pip
Read from stdin (standard input)
Get the class name of an instance
Check if a string is empty
Pad zeroes to a string
Delete an element from a dictionary
Check if a string is a float
Count the occurrences of an item in a list
Remove an element from a list by index
Use static methods
Remove a trailing newline
Print literal curly-brace characters in a string and also use .format on it
Exit/deactivate a virtualenv
Determine the type of an object
Limit floats to two decimal points
Know if an object has an attribute
Select an item from a list randomly
Read a file line-by-line into a list
Call a function of a module by using its name
Get the number of elements in a list
Print without a newline or space
Sort a list of dictionaries by a value of the dictionary
Remove a key from dictionary
Rename column names with Pandas
Lowercase a string
Upgrade all Python packages with pip
Get a substring of a string
Get the last element of a list
Parse a string to a float or integer
Convert a string into datetime format
Access environment variable values
Print coloured text on the terminal
Find current directory of a file
Change the size of figures drawn with Matplotlib
Manually raise an exception
Delete a file or folder
Split a list into evenly sized parts
Select rows from a DataFrame based on column values with Pandas
Install pip on Windows
Check if a given key already exists in a dictionary
Iterate over rows in a DataFrame for Pandas
Make function decorators and chain them together
Pass a variable by reference
Make a time delay
Convert bytes to a string
Copy a file
Concatenate two lists
Add new keys to a dictionary
Catch multiple exceptions in a single 'except' block
Check if a list is empty
Get the current time
Sort a dictionary by value
Use global variables in a function
List all files of a directory
Iterate over dictionaries using for loops
Check if a string contains a substring
Find the index of an item in a list
Understand how slice notation works
Make a flat list out of a list of lists
Accesses the index in for loops
Safely create a nested directory
Merge two dictionaries in a single expression
Check whether a file exists without exceptions
Convert a dictionary into a list
Convert a list into a dictionary
Duplicate a file
Append text in a text file
Use for loops
Deploy a web app to Heroku
Schedule a Python script for execution at a specific time every day
Store Python passwords securely on Windows, Mac, and Linux
Do dictionary comprehension
Do list comprehension
Create a virtual environment
Create a new file
Merge two lists
Extract items from two different lists into one list
Check if a text file is empty
Randomly select an item from a list
Generate a random integer
Break a while loop
Create a pandas DataFrame from a dictionary
Create a pandas DataFrame from a list
Get the last item of a list
Delete a column from a pandas dataframe
Access a column of a pandas dataframe
Create a class
Make a webpage request
Get the first two characters of a string
Loop through two lists at the same time
Recommended Course

Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.