In this tutorial, we will be discussing how to create a graphical interface using the PySimpleGUI library as part of the Evidencia 2 assignment by Luis Martin López Garay (A00835632).
PySimpleGUI is a simple, yet powerful library for creating graphical user interfaces in Python. It provides an easy-to-use interface for building windows, buttons, input fields, and more. In this tutorial, we will walk through the steps to create a basic GUI using PySimpleGUI.
Step 1: Installing PySimpleGUI
Before we can start creating our GUI, we need to install the PySimpleGUI library. You can do this using pip by running the following command in your terminal:
pip install PySimpleGUI
Step 2: Importing PySimpleGUI
Once PySimpleGUI is installed, we can import it into our Python script using the following line of code:
import PySimpleGUI as sg
Step 3: Creating a Simple GUI Window
To create a basic GUI window, we can use the sg.Window
class. Here’s an example of how to create a simple window with a title and some text:
layout = [
[sg.Text('Hello, World!')],
[sg.Button('OK')]
]
window = sg.Window('My First GUI', layout)
In this example, we have defined a layout for our window with a text element (‘Hello, World!’) and a button (‘OK’). We then create a window object with the title ‘My First GUI’ and the defined layout.
Step 4: Handling Events
Next, we need to handle events within our GUI. This can be done using a while loop that calls the read
method on the window object. Here’s an example of how to handle events for our simple GUI window:
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED or event == 'OK':
break
window.close()
In this code snippet, we use a while loop to continuously read events from the window. If the event is equal to sg.WINDOW_CLOSED
or ‘OK’, we break out of the loop and close the window.
Step 5: Adding Input Fields
We can also add input fields to our GUI window using the sg.Input
class. Here’s an example of how to add a text input field to our window:
layout = [
[sg.Text('Enter your name:')],
[sg.Input()],
[sg.Button('Submit')]
]
window = sg.Window('Input Example', layout)
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED or event == 'Submit':
break
window.close()
In this example, we have added a text input field to our GUI window with the text ‘Enter your name:’. We then read the input value when the ‘Submit’ button is clicked.
Step 6: Conclusion
In this tutorial, we have learned how to create a graphical user interface using PySimpleGUI. We have covered basic window creation, event handling, and adding input fields to our GUI. With this knowledge, you can start building more complex and interactive GUI applications in Python. Have fun exploring the possibilities of PySimpleGUI!