Getting Started with PySimpleGUI – Part 4: Managing Multiple Windows and Saving User Input

Posted by


In this tutorial, we will learn how to create multiple windows using PySimpleGUI and how to store user input in variables.

Creating Multiple Windows:
PySimpleGUI allows us to easily create multiple windows in our application. Each window is created using the sg.Window() function, which takes a title for the window as its argument. To display the window, we use the window.read() function.

Let’s start by creating a simple program that demonstrates how to create multiple windows. Here’s an example code:

import PySimpleGUI as sg

# Create Window 1
window1 = sg.Window('Window 1', [[sg.Text('This is window 1')]])

# Create Window 2
window2 = sg.Window('Window 2', [[sg.Text('This is window 2')]])

# Display Window 1
while True:
    event, values = window1.read()
    if event == sg.WIN_CLOSED:
        break

# Display Window 2
while True:
    event, values = window2.read()
    if event == sg.WIN_CLOSED:
        break

window1.close()
window2.close()

In this code, we first create two windows, window1 and window2, each with a simple Text element. We then use a while loop to display each window. The loop continues until the user closes the window by clicking the close button.

Storing User Input:
Now, let’s look at how we can store user input in variables. PySimpleGUI provides different element types such as InputText, InputCombo, and Checkbox to take user input.

Here’s an example code that demonstrates how to store user input in variables:

import PySimpleGUI as sg

# Create a simple form
layout = [
    [sg.Text('Enter your name:'), sg.InputText(key='name')],
    [sg.Button('Submit')]
]

window = sg.Window('User Input', layout)

while True:
    event, values = window.read()

    if event == sg.WIN_CLOSED:
        break

    if event == 'Submit':
        name = values['name']
        sg.Popup(f'Hello {name}!')

window.close()

In this code, we create a simple form with an InputText element to take the user’s name as input. When the user clicks the Submit button, we retrieve the input value using values[‘name’] and store it in a variable called name. Finally, we display a popup message using sg.Popup() that greets the user with their name.

Conclusion:
In this tutorial, we learned how to create multiple windows using PySimpleGUI and how to store user input in variables. With this knowledge, you can now create more complex GUI applications that involve multiple screens and user interaction. I hope you found this tutorial helpful and are excited to explore more of the capabilities of PySimpleGUI.

0 0 votes
Article Rating
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@oshxde7697
1 month ago

let me retake the test-Andrew

@Kdevana
1 month ago

Waiting for the next video to see how you stored that data to any location