Building Your Recipe Recommendation App with PySimpleGUI

A Step-by-Step Guide

In this post, we'll walk through creating a Recipe Recommendation App which we introduced in the last post using Python and PySimpleGUI.

 

This app will allow users to filter recipes based on dietary needs, view images of selected recipes, and save their favorites.

 

By the end, you'll have a fully functioning GUI app that's not only practical but also a fun project to enhance your Python skills.

 

Let's break down the code step by step:

 

Step 1: Importing PySimpleGUI and Setting Up Recipes

 

import PySimpleGUI as sg

 

# Sample Recipes

recipes = {

    'Spaghetti': {'ingredients': ['pasta', 'tomato sauce', 'cheese'], 'tags': ['vegetarian'], 'image': 'spaghetti.png'},

    'Grilled Chicken': {'ingredients': ['chicken', 'spices', 'lemon'], 'tags': ['non-vegetarian'], 'image': 'chicken.png'},

    'Vegan Salad': {'ingredients': ['lettuce', 'tomato', 'cucumber'], 'tags': ['vegan', 'gluten-free'], 'image': 'salad.png'},

}

 

Here, we start by importing PySimpleGUI (abbreviated as sg) and defining a dictionary of sample recipes.

 

Each recipe includes a list of ingredients, tags for dietary restrictions, and an image filename.

 

This structure which uses Python Dictionary and List makes it easy to manage and display the information within the GUI.

 

Step 2: Creating the Save Function

 

def save_recipe(recipe_name, recipe_details):

    ingredients = ', '.join(recipe_details['ingredients'])

    tags = ', '.join(recipe_details['tags'])

    formatted_recipe = f"Recipe: {recipe_name}\nIngredients: {ingredients}\nTags: {tags}\n"

 

    with open('favorites.txt', 'a') as file:

        file.write(formatted_recipe)

    sg.popup('Saved!', f'{recipe_name} has been saved to your favorites.')

 

The save_recipe function formats the selected recipe's details into a string and saves it to a file named favorites.txt.

 

If the user selects a recipe and clicks "Save to Favorites," this function is triggered.

 

A popup window confirms that the recipe has been saved.

 

Step 3: Filtering Recipes by Dietary Needs

 

def filter_recipes(dietary_needs, recipes):

    filtered = [recipe for recipe, details in recipes.items() if dietary_needs in details['tags']]

    return filtered

 

This function helps to filter recipes based on the user's selected dietary needs.

 

For example, if a user is looking for vegan recipes, the function will return only the recipes tagged as vegan.

 

Step 4: Designing the GUI Layout

 

layout = [

    [sg.Text('Select Dietary Needs:')],

    [sg.Checkbox('Vegetarian', key='-VEG-', enable_events=True),

     sg.Checkbox('Vegan', key='-VEGAN-', enable_events=True),

     sg.Checkbox('Gluten-Free', key='-GF-', enable_events=True)],

    [sg.Listbox(values=list(recipes.keys()), size=(30, 6), key='-RECIPE LIST-', enable_events=True)],

    [sg.Image(key='-IMAGE-')],

    [sg.Button('Save to Favorites'), sg.Button('Exit')]

]

 

In this step, we define the layout of our GUI.

 

The layout includes checkboxes for dietary preferences, a Listbox to display recipe names, an Image element to show the selected recipe's image, and buttons to save a recipe or exit the application.

Layout of GUI

 

Step 5: Handling Events and Updating the GUI

 

window = sg.Window('Recipe Recommendation App', layout)

 

selected_recipe = None

 

while True:

    event, values = window.read()

 

    if event in (sg.WINDOW_CLOSED, 'Exit'):

        break

 

    if event == '-RECIPE LIST-':

        selected_recipe = values['-RECIPE LIST-'][0] if values['-RECIPE LIST-'] else None

        if selected_recipe:

            display_image = recipes[selected_recipe]['image']

            try:

                window['-IMAGE-'].update(filename=display_image)

            except Exception as e:

                sg.popup_error(f"Failed to load image: {e}")

 

    if event == 'Save to Favorites':

        if selected_recipe:

            save_recipe(selected_recipe, recipes[selected_recipe])

        else:

            sg.popup_error('No recipe selected!', 'Please select a recipe to save.')

 

    dietary_filter = []

    if values['-VEG-']:

        dietary_filter.append('vegetarian')

    if values['-VEGAN-']:

        dietary_filter.append('vegan')

    if values['-GF-']:

        dietary_filter.append('gluten-free')

 

    if dietary_filter:

        filtered_recipes = []

        for need in dietary_filter:

            filtered_recipes += filter_recipes(need, recipes)

        window['-RECIPE LIST-'].update(values=filtered_recipes)

    else:

        window['-RECIPE LIST-'].update(values=list(recipes.keys()))

 

window.close()

 

This is the heart of the app where the event loop continuously checks for user interactions:

 

Event Handling:

  • The event variable tracks what the user clicks or selects.

  • If they select a recipe, the app updates the image display accordingly.

  • If they click "Save to Favorites," the app saves the selected recipe.

 

Filtering:

  • The code checks which dietary checkboxes are selected and filters the recipes accordingly.

  • The Listbox is then updated to show only the filtered recipes.

 

Error Handling:

  • The app includes error handling to manage cases like failed image loading or no recipe being selected when attempting to save.

Wrapping Up!

 

By following these steps, you've now built a dynamic Recipe Recommendation App with Python and PySimpleGUI!

 

This app not only helps users find and save recipes based on dietary needs but also makes it easier to visualize and interact with the information.

Download the completed code below:

adv_recipe.pdf29.40 KB β€’ PDF File

Coding with a Smile πŸ€£ πŸ˜‚

The Mighty Regex:

Using regular expressions is like wielding a magical incantation.

It’s powerful and a bit arcane, but once mastered, it can transform even the messiest strings into something usable.

Let’s Inspire Future AI Coders Together! β˜•

 

I’m excited to continue sharing my passion for Python programming and AI with you all. If you’ve enjoyed the content and found it helpful, do consider supporting my work with a small gift. Just click the link below to make a difference – it’s quick, easy, and every bit helps and motivates me to keep creating awesome contents for you.

Thank you for being amazing!

Ready for More Python Fun? πŸ“¬

Subscribe to our newsletter now and get a free Python cheat sheet! πŸ“‘ Dive deeper into Python programming with more exciting projects and tutorials designed just for beginners.

Keep learning, keep coding πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’», and keep discovering new possibilities! πŸ’»βœ¨

Enjoy your journey into artificial intelligence, machine learning, data analytics, data science and more with Python!

Stay tuned for our next exciting project in the following edition!

Happy coding!πŸš€πŸ“Šβœ¨

πŸŽ‰ We want to hear from you! πŸŽ‰ How do you feel about our latest newsletter? Your feedback will help us make it even more awesome!

Login or Subscribe to participate in polls.