I have 3 labels and entry boxes, one is Sandwich, the other is drinks and the third one for showing their calculated costs.
There, I expect the user to enter the number of sandwiches and drinks they've had and calculate their price and show it in the third box by using this formula:
totalCost = (cod*30)+(cos*100)
costtotal.set(totalCost)
And it does so perfectly.
However, the problem is, that for example a user doesn't enter anything in the drinks field, I want the interpreter to interpret that empty field as 0 and calculate the sum. But, my program doesn't calculate it if any of the two fields (Drinks and Sandwiches) are empty. So, to counter this I tried:
if not drinks.get():
yourVar = "0"
cod=float(yourVar)
This is the error message I get:
File "C:/Users/Dell E6430/Desktop/trying.py", line 18, in Ref cod=float(drinks.get()) ValueError: could not convert string to float:
I don't get this error message when I input both fields.
However, it isn't working and the result is same. So, how do I solve that? Thanks.
Here's the full code:
from tkinter import*
root=Tk()
root.geometry("1600x800+0+0")
#------- convert to string
drinks=StringVar()
costtotal=StringVar()
sandwich=StringVar()
#----Frame
f1=Frame(root,width=800, height=700,relief=SUNKEN)
f1.pack(side=LEFT)
def Ref():
cos=float(sandwich.get())
cod=float(drinks.get())
if not drinks.get():
yourVar = "0"
cod=float(yourVar)
totalCost = (cod*30)+(cos*100)
costtotal.set(totalCost)
lblSandwich=Label(f1,font=('arial',16,'bold'),text="Sandwich" , bd=16, anchor='w')
lblSandwich.grid(row=0,column=0)
txtSandwich=Entry(f1,font=('arial',16,'bold'),textvariable=sandwich,bd=10,insertwidth=4,bg="powder blue",justify='right')
txtSandwich.grid(row=0,column=1)
lblDrinks=Label(f1,font=('arial',16,'bold'),text="Drinks" , bd=16, anchor='w')
lblDrinks.grid(row=1,column=0)
txtDrinks=Entry(f1,font=('arial',16,'bold'),textvariable=drinks,bd=10,insertwidth=4,bg="powder blue",justify='right')
txtDrinks.grid(row=1,column=1)
lblcostTotal=Label(f1,font=('arial',16,'bold'),text="Cost of Drinks" , bd=16, anchor='w')
lblcostTotal.grid(row=2,column=0)
txtcostTotal=Entry(f1,font=('arial',16,'bold'),textvariable=costtotal,bd=10,insertwidth=4,bg="powder blue",justify='right')
txtcostTotal.grid(row=2,column=1)
btnTotal=Button(f1,padx=16,pady=8,bd=16,fg="black",font=('arial',16,'bold'),width=10,text="Total", bg="Powder Blue"\
,command=Ref).grid(row=7,column=1)
root.mainloop()
EDIT: By doing
cod=drinks.get()
if not drinks.get():
yourVar = "0"
cod=float(yourVar)
else:
cod=float(drinks.get())
the program runs fine now.