Home > Back-end >  Add prices to combobox values and display the total after selection on buttonclick Tkinter
Add prices to combobox values and display the total after selection on buttonclick Tkinter

Time:04-26

Trying to add prices for different sizes and toppings with button-click to display total order.

def show_answer():
print (box1.get())
print (box2.get())
print (box3.get())

Label (main, text="Select Scoops: ").grid(row=5, column=1)
Scoops =['One','Two','Three']
box2 = ttk.Combobox (main, values=Scoops)
box2.grid(row=5, column=2)

Label (main, text="Select Topping: ").grid(row=7, column=1)
Toppings =['Nuts','Whipped Cream','Cherries']
box3 = ttk.Combobox (main, values=Toppings)
box3.grid(row=7, column=2)

Button (main, text='Order Now', command=show_answer).grid (row=9, column=2, sticky=W, pady=6)

CodePudding user response:

You can use dictionaries to store the prices for different scoops and toppings and then you can calculate the total price based on selected scoop and topping inside show_answer():

...
def show_answer():
    scoop = box2.get()
    topping = box3.get()
    if scoop and topping:
        total_price = Scoops[scoop]   Toppings[topping]
        total_lbl['text'] = f'Total price is ${total_price}'
    else:
        total_lbl['text'] = 'Select both scoop and topping'

Label (main, text="Select Scoops: ").grid(row=5, column=1)
Scoops = {
    'One': 10,
    'Two': 18,
    'Three': 24
}
box2 = ttk.Combobox (main, values=list(Scoops.keys()))
box2.grid(row=5, column=2)

Label (main, text="Select Topping: ").grid(row=7, column=1)
Toppings = {
    'Nuts': 3.5,
    'Whipped Cream': 2.5,
    'Cherries': 5
}
box3 = ttk.Combobox (main, values=list(Toppings.keys()))
box3.grid(row=7, column=2)

Button(main, text='Order Now', command=show_answer).grid(row=9, column=2, sticky=W, pady=6)

# label to show the total price
total_lbl = Label(main)
total_lbl.grid(row=10, column=1, columnspan=2)
...
  • Related