Creating a Graphical User Interface for a Madlib Game using PySimpleGUI – Part 3

Posted by

Developing a GUI for a Madlib game in PySimpleGUI – Part 3

Developing a GUI for a Madlib game in PySimpleGUI – Part 3

In this tutorial, we will continue to develop a GUI for a Madlib game using PySimpleGUI. In Part 2, we created the basic layout for our GUI and added input fields for the user to enter words to fill in the Madlib.

Step 3: Adding a Submit button

Now, let’s add a Submit button that the user can click after filling in all the input fields. This button will trigger the function that generates the final Madlib story.


<button type="submit" id="submitBtn">Submit</button>

We can use the following code snippet to add a Submit button to our GUI:

import PySimpleGUI as sg

layout = [
    [sg.Text('Enter a noun:'), sg.InputText(key='noun')],
    [sg.Text('Enter a verb:'), sg.InputText(key='verb')],
    [sg.Button('Submit')]
]

window = sg.Window('Madlib Game').layout(layout)

while True:
    event, values = window.read()
    
    if event == sg.WIN_CLOSED:
        break
    
    if event == 'Submit':
        noun = values['noun']
        verb = values['verb']
        # Generate Madlib story using the entered words
        # The code for generating the Madlib story will go here

Step 4: Generating the Madlib story

Next, we need to write the code that generates the final Madlib story using the words entered by the user. This code will replace placeholders in a template with the user’s input to create the final story.

Here is an example of how we can generate the final Madlib story:

madlib_template = "Once upon a time, there was a {noun} who loved to {verb}."
madlib_story = madlib_template.format(noun=noun, verb=verb)

Step 5: Displaying the Madlib story

Finally, we can display the generated Madlib story to the user. We can use a Popup window to show the story once it has been generated:

sg.popup(madlib_story, title='Madlib Story')

That’s it! With these steps, we have successfully developed a GUI for a Madlib game in PySimpleGUI. The user can enter words, click the Submit button, and see the final Madlib story. Have fun playing around with different templates and creating your own Madlibs!