Introduction
A shopping list application helps users organize and keep track of items they need to purchase. This program demonstrates how to create a basic interactive shopping list application using Python’s Tkinter library, allowing users to add, delete, and view items in a list.
Objective
The objective of this program is to build a user-friendly shopping list application with basic functionality to manage items effectively.
Python Code
import tkinter as tk from tkinter import messagebox class ShoppingListApp: def __init__(self, root): self.root = root self.root.title("Shopping List Application") # Input field for new items self.entry = tk.Entry(root, width=40) self.entry.pack(pady=10) # Add item button self.add_button = tk.Button(root, text="Add Item", command=self.add_item) self.add_button.pack() # Listbox to display items self.listbox = tk.Listbox(root, width=50, height=15) self.listbox.pack(pady=10) # Delete item button self.delete_button = tk.Button(root, text="Delete Selected Item", command=self.delete_item) self.delete_button.pack() def add_item(self): item = self.entry.get().strip() if item: self.listbox.insert(tk.END, item) self.entry.delete(0, tk.END) else: messagebox.showwarning("Input Error", "Please enter an item.") def delete_item(self): try: selected_index = self.listbox.curselection()[0] self.listbox.delete(selected_index) except IndexError: messagebox.showwarning("Selection Error", "Please select an item to delete.") if __name__ == "__main__": root = tk.Tk() app = ShoppingListApp(root) root.mainloop()
Program Explanation
This Python program uses the Tkinter library to create a shopping list application. Here’s a breakdown of the program structure:
ShoppingListApp
: The main application class that initializes the GUI elements and provides functionality to manage the shopping list.add_item
: Adds a new item to the listbox when the user enters text and clicks the “Add Item” button.delete_item
: Removes the selected item from the listbox when the user clicks the “Delete Selected Item” button.
Steps to Run the Program
- Ensure Python is installed on your system.
- Copy the code into a file named
shopping_list_app.py
. - Open a terminal or command prompt and navigate to the directory containing the file.
- Run the script using the command:
python shopping_list_app.py
. - Use the input field to add items and the buttons to manage the shopping list.