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

Posted by

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

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

In this tutorial, we will continue our journey of developing a graphical user interface (GUI) for a Madlib game using PySimpleGUI. In part 3, we worked on creating input fields for the user to enter their words and displayed the finalized Madlib story. Now, we will focus on adding a button to reset the game and start a new Madlib story.

Step 1: Create a Reset Button

First, we need to create a button that will reset the game and allow the user to start over. We can do this by adding the following code snippet to our existing PySimpleGUI code:


<button = sg.Button('Reset Game')

This code snippet creates a new button with the label ‘Reset Game’. You can customize the label to something else if desired.

Step 2: Add Functionality to the Reset Button

Next, we need to add functionality to the reset button so that when it is clicked, the game is reset and the user can start a new Madlib story. We can accomplish this by adding the following code snippet:


event, values = window.read()
if event == 'Reset Game':
for key in values:
window[key].update('')
window['output'].update('')

With this code snippet, we are checking if the ‘Reset Game’ button is clicked. If it is, we iterate through all the input fields and clear the text inside them. We also clear the output field that displays the Madlib story.

Step 3: Finalize the GUI

Finally, we need to update our GUI layout to include the new reset button. Here is the complete code snippet for the GUI layout:


layout = [
[sg.Text('Enter a noun:'), sg.InputText(key='noun')],
[sg.Text('Enter a verb:'), sg.InputText(key='verb')],
[sg.Text('Enter an adjective:'), sg.InputText(key='adjective')],
[sg.Text('Enter an adverb:'), sg.InputText(key='adverb')],
[sg.Button('Generate Madlib'), button],
[sg.Text('Output:'), sg.Text(size=(40, 10), key='output')]
]

With this layout, we have added the reset button to our GUI. The user can now input words, generate a Madlib story, and reset the game to start a new story.

Conclusion

Developing a GUI for a Madlib game in PySimpleGUI is a fun and engaging project. With the addition of a reset button, our game is now complete. Users can input words, see the finalized story, and start a new game with the click of a button. Try customizing the game further by adding more input fields or styling the GUI to your liking.

Stay tuned for more tutorials on PySimpleGUI and game development!