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.
You cannot run float()
over anything that is not a valid number. You should probably first check if your get()
is returning a number with isnumeric()
then if true run float if not set value to zero. That will handle anything not a number and even if it is a letter.
Note I have cleaned up your code a bit to more closely follow PEP8 standards as well as updated your import to help prevent overwriting. import tkinter as tk
is always preferred over *
.
Try this:
import tkinter as tk
root = tk.Tk()
root.geometry("1600x800+0+0")
cost_total = tk.StringVar()
sandwich = tk.StringVar()
drinks = tk.StringVar()
f1 = tk.Frame(root, width=800, height=700, relief='sunken')
f1.pack(side='left')
def ref():
d = drinks.get()
s = sandwich.get()
if d.isnumeric():
cod = float(d)
else:
cod = 0
if s.isnumeric():
cos = float(s)
else:
cos = 0
total_cost = (cod * 30) + (cos * 100)
cost_total.set(total_cost)
tk.Label(f1, font=('arial', 16, 'bold'), text="Sandwich", bd=16, anchor='w').grid(row=0, column=0)
tk.Entry(f1, font=('arial', 16, 'bold'), textvariable=sandwich, bd=10, insertwidth=4,
bg="powder blue", justify='right').grid(row=0, column=1)
tk.Label(f1, font=('arial', 16, 'bold'), text="Drinks", bd=16, anchor='w').grid(row=1, column=0)
tk.Entry(f1, font=('arial', 16, 'bold'), textvariable=drinks, bd=10, insertwidth=4,
bg="powder blue", justify='right').grid(row=1, column=1)
tk.Label(f1, font=('arial', 16, 'bold'), text="Cost of Drinks", bd=16, anchor='w').grid(row=2, column=0)
tk.Entry(f1, font=('arial', 16, 'bold'), textvariable=cost_total, bd=10, insertwidth=4,
bg="powder blue", justify='right').grid(row=2, column=1)
tk.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()
Results:
To answer you question in the comments you can use a list or a couple list to manage large amounts of fields. Consider the below and let me know if you have any questions.
Code:
import tkinter as tk
list_of_foods = [['Coffie', 30], ['Tea', 20], ['Sandwich', 100], ['Apple', 50]]
def ref():
total = 0
for ndex, entry in enumerate(entry_list):
value = entry.get()
if value.isnumeric():
total += float(value) * list_of_foods[ndex][1]
print(total)
else:
total += 0
double_var.set(total)
root = tk.Tk()
double_var = tk.DoubleVar(root, value=0)
entry_list = []
for ndex, sub_list in enumerate(list_of_foods):
tk.Label(root, text=sub_list[0]).grid(row=ndex, column=0)
entry_list.append(tk.Entry(root))
entry_list[-1].grid(row=ndex, column=1)
tk.Entry(root, textvariable=double_var).grid(row=len(entry_list)+2, column=0, columnspan=2)
tk.Button(root, text='Total', command=ref).grid(row=len(entry_list)+3, column=0, columnspan=2)
root.mainloop()
Results:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.