Feb-12-2021, 08:21 PM
(This post was last modified: Feb-12-2021, 08:37 PM by deanhystad.)
A radio button group is not a good choice for this application. First you have to select an item, then you add it to the cart. Two clicks. Unless selecting an item brings up additional information to view before making a selection you should use a push button.
In the code below I make a button for each item in the inventory. Clicking the item adds it to the cart. The cart displays the item name and buttons to add more of the same, or to remove items.
There are likely widgets better than frame for displaying the cart, but this was easy and I am lazy.
In the code below I make a button for each item in the inventory. Clicking the item adds it to the cart. The cart displays the item name and buttons to add more of the same, or to remove items.
There are likely widgets better than frame for displaying the cart, but this was easy and I am lazy.
import tkinter as tk root = tk.Tk() root.title("Super Market") food = { "Rice": 0.99, "Spaghetti": 0.95, "Ice cream": 3.44, "Pizza": 7.50, "Cheese": 2.10, "Cheddar": 0.45, "Cherry": 0.88, "Banana": 0.40, "Apple": 0.67, "Meat": 7.28, "Fish": 9.72, "Orange": 0.62, "Orange juice": 2.10, "Chocolate": 0.99, "Bread": 0.55} inventory = tk.Frame(root) inventory.grid(row=0, column=0) shopping_cart = {} def update_cart(): print(shopping_cart) for item in cart.winfo_children(): item.grid_forget() item.destroy() for r, item in enumerate(shopping_cart): text = f'{shopping_cart[item]} x {item}' tk.Label(cart, text=text, width=20) \ .grid(row=r, column=0) tk.Button(cart, text=' + ', command=lambda n=item: add_item(n)) \ .grid(row=r, column=1) tk.Button(cart, text=' - ', command=lambda n=item: remove_item(n)) \ .grid(row=r, column=2) def add_item(item): shopping_cart[item] = shopping_cart.get(item, 0) + 1 update_cart() def remove_item(item): if item in shopping_cart: shopping_cart[item] -= 1 if shopping_cart[item] <= 0: shopping_cart.pop(item) update_cart() for item in food: button = tk.Button(inventory, text=item, width=20, command=lambda n=item: add_item(n)) button.pack(side=tk.TOP) cart = tk.Frame(root) cart.grid(row=0, column=1) root.mainloop()