Having trouble for calculating total amount of Items

60 Views Asked by At

I'm having trouble understanding why some of the first 2 items on my list is not being calculated. What am I missing?

code:

from tkinter import *
root = Tk()
root.geometry('300x200')
root.title("Grade Calculator")

def exitProgram():
root.destroy()

def  calculate():
    totalcost = 0
    if CheckVar1.get() == 1:
        totalcost += 10
    if CheckVar2.get() == 1:
        totalcost += 2.50
    if CheckVar3.get() == 1:
        totalcost += 4
        label_2.config(text="Total cost: $"+str(totalcost))

CheckVar1 = IntVar()
CheckVar2 = IntVar()
CheckVar3 = IntVar()

label_1 = Label(root, text="Select from the menu: ",font= 

("bold", 10)) label_1.place(x=20,y=10)

Checkbutton(root, text = "Premium Whapper ($10.0)", variable = CheckVar1, onvalue = 1, offvalue = 0).place(x=50,y=40)
Checkbutton(root, text = "Inca cola ($2.50)", variable = 
CheckVar2, onvalue = 1, offvalue = 0).place(x=50,y=65)
Checkbutton(root, text = "Smash potatoes ($4.0)", variable 
= CheckVar3, onvalue = 1, offvalue = 0).place(x=50,y=90)
label_2 = Label(root, text="Total cost: $0 ",font=("bold", 
10))
label_2.place(x=30,y=120)

Button(root, text='Calculate 
Cost',command=calculate).place(x=20,y=150)
Button(root, text='Quit',width="7", 
command=exitProgram).place(x=130,y=150)

root.mainloop()
2

There are 2 best solutions below

0
On

You only set the label if CheckVar3 is true:

if CheckVar3.get() == 1:
    totalcost += 4
    label_2.config(text="Total cost: $"+str(totalcost))

Because of an issue with your indentation, it should be:

if CheckVar3.get() == 1:
    totalcost += 4

label_2.config(text="Total cost: $"+str(totalcost))
0
On

You have tons of Indentation mistakes and disrupted control flow! Anyways, here is the working code:

from tkinter import *

def exitProgram():
    root.destroy()

def calculate():
    global label_2, totalcost
    if CheckVar1.get() == 1:
        totalcost += 10
    if CheckVar2.get() == 1:
        totalcost += 2.50
    if CheckVar3.get() == 1:
        totalcost += 4
    label_2.config(text="Total cost: $"+str(totalcost))

totalcost = 0
root = Tk()
root.geometry('300x200')
root.title("Grade Calculator")

CheckVar1 = IntVar()
CheckVar2 = IntVar()
CheckVar3 = IntVar()

label_1 = Label(root, text="Select from the menu: ",font=("bold", 10))
label_1.place(x=20,y=10)

Checkbutton(root, text = "Premium Whapper ($10.0)", variable = CheckVar1, onvalue = 1, offvalue = 0).place(x=50,y=40)
Checkbutton(root, text = "Inca cola ($2.50)", variable =CheckVar2, onvalue = 1, offvalue = 0).place(x=50,y=65)
Checkbutton(root, text = "Smash potatoes ($4.0)", variable= CheckVar3, onvalue = 1, offvalue = 0).place(x=50,y=90)
label_2 = Label(root, text="Total cost: $0 ",font=("bold",10))
label_2.place(x=30,y=120)

Button(root, text='Calculate Cost',command=calculate).place(x=20,y=150)
Button(root, text='Quit',width="7",command=exitProgram).place(x=130,y=150)

root.mainloop()