如何将Tkinter Spinbox与添加到购物车功能关联实现商品选购及总价计算
Got it, let's fix up your code to add the cart functionality you're looking for. Here's the modified version with clear explanations of the key changes:
Modified Code
from tkinter import * # Product data price_audible = ['$1.99', '$1.50', '$1.00', '$1.99', '$1.50', '$1.00', '$1.99', '$1.50', '$1.00', '$1.99'] description_audible = ['1: Aaaaaa', '2: bbbbbb', '3: ccccccccc', '4: dddddddddd', '5:eeeeeeee', '6: fffffff', '7: gggggggg', '8: hhhh', '9: ii', '10: jjjjjjjjjjjjjjjjj'] # Build the initial product list display audible_newlist = '' for m in range(10): var_1 = f"#{description_audible[m]}\n({price_audible[m]})\n" audible_newlist += var_1 # Main window setup dash_1 = Tk() dash_1.configure(bg='red') dash_1.title("Amazon Bestsellers Audible") # StringVar for product list display show_window = StringVar() show_window.set(audible_newlist) # Cart variables cart = [] cart_display = StringVar() cart_display.set("Cart is empty.") total_display = StringVar() total_display.set("Total: $0.00") # Fixed typo: catagory → category def audible_category(): new_pc = Toplevel(dash_1) new_pc.title('Amazon Bestsellers PC') Label(new_pc, text="Amazon Bestsellers PC", font=('Arial', 14), bg='red', fg='floralwhite').pack() Label(new_pc, textvariable=show_window, justify=LEFT, bg='light yellow', takefocus=True).pack() # Add to cart function def add_to_cart(): try: # Get selected item number (convert to integer) item_num = int(spin_box.get()) if not (1 <= item_num <= 10): raise ValueError except ValueError: cart_display.set("Please select a valid item (1-10)!") return # Get item details (adjust index for 0-based list) index = item_num - 1 item_desc = description_audible[index] item_price_str = price_audible[index] item_price = float(item_price_str.replace('$', '')) # Add item to cart cart.append((item_desc, item_price)) # Update cart display cart_text = "Items in cart:\n" for desc, price in cart: cart_text += f"- {desc} (${price:.2f})\n" cart_display.set(cart_text) # Calculate and update total total = sum(price for _, price in cart) total_display.set(f"Total: ${total:.2f}") # Main window widgets Label(dash_1, text="Amazon Bestsellers Audible", font=('Arial', 14), bg='red', fg='floralwhite').pack() # Fixed: use textvariable instead of text for StringVar Label(dash_1, textvariable=show_window, bg='red', fg='white', justify=LEFT).pack() # Spinbox: fixed reference (split pack() to keep variable) and set range to 1-10 spin_box = Spinbox(dash_1, from_=1, to=10, fg='black', width=2, justify=RIGHT, relief='flat', bg='red') spin_box.pack(pady=5) # Add to cart button with command Button(dash_1, text='Add to cart', command=add_to_cart).pack(pady=5) # Cart and total display labels Label(dash_1, textvariable=cart_display, bg='red', fg='white', justify=LEFT).pack(pady=5) Label(dash_1, textvariable=total_display, bg='red', fg='white', font=('Arial', 12, 'bold')).pack(pady=5) # Radiobutton: use BooleanVar instead of IntVar for better clarity conction = BooleanVar() Radiobutton(dash_1, text='Amazon Audible', value=True, variable=conction, command=audible_category).place(x=0, y=0) dash_1.mainloop()
Key Changes Explained
- Spinbox Fix: Split the Spinbox creation and packing so we can retrieve its value later (since
pack()returnsNone). Also adjusted the range to1-10to match your product numbers. - Cart Setup: Added a
cartlist to store selected items, plus twoStringVars to display the cart contents and total price. - Add to Cart Function:
- Validates the Spinbox input to ensure it's a number between 1 and 10.
- Retrieves the selected item's details using the Spinbox value (adjusted for 0-based list indexing).
- Converts the price string to a float for accurate total calculation.
- Updates the cart display and total price every time an item is added.
- Widget Fixes: Corrected the main window's product list label to use
textvariableinstead oftext(sinceshow_windowis aStringVar), fixed the typo inaudible_catagory, and usedBooleanVarfor the radiobutton variable for better clarity. - UI Improvements: Added padding (
pady) to widgets for better spacing, and styled the total label to stand out.
Now when you select an item number in the Spinbox and click "Add to cart", the item will be added to your cart, and you'll see the updated list of items and total price in the main window.
内容的提问来源于stack exchange,提问作者Sharafat
相关产品推荐
相关产品推荐

