python - Python 的整数和浮点数问题
问题描述
在过去的几个月里,我一直在制作一个代码,可以从条目中找到最便宜的产品。一切正常,直到我按下加号按钮添加新项目。填写完字段后,ValueError: could not convert string to float:
即使我输入了有效数字 (1),我也会得到错误的输出。
然后我被建议执行以下代码:
c = int(c)
cp = int(cp)
ca = int(ca)
ca = float(c)/float(cp)
只为给我输出
ValueError: invalid literal for int() with base 10: ''
我不知道我对前面几行的编码方式是否有问题,或者我是否做错了什么。
我已将代码上传到 Repl,我还将把代码放在 Repl 链接下方:https ://repl.it/@NaiduBoys/code?language=tkinter&folderId=
代码:
##!! Must be run in an IDLE !!##
from tkinter import * #Import the Tkinter module
from tkinter import messagebox #Imports the message box module
from tkinter import font #Imports fonts from tkinter
import json #Imports JSON
a = ('') #Variable for price and quantity/mass
b = ('') #^
c = ('') #^
d = ('') #^
e = ('') #^
f = ('') #^h
r = ('') #Result Var
aa = ('')
ba = ('')
ca = ('')
c = 1
cp = 1
ca = 1
count = 2 #For extra Fields
master = Tk() #Tkinter
m = StringVar(master) #Defines m as yhe variable from the option menu
c = StringVar(master) #Defines m as yhe variable from the option menu
entry5 = Entry(master) #Entry Feilds (Variables)
entry6 = Entry(master)
def addnew():
global count
count = count+1
if count == 3:
Label(master, text="Item #3", font=("Helvetica", 17, "bold underline")).grid(row=8) #2nd Item Fields
Label(master, textvariable=c).grid(row=9)
Label(master, textvariable=m).grid(row=10)
entry5 = Entry(master) #Entry Feilds (Variables)
entry6 = Entry(master)
entry5.grid(row=9, column=1) #Puts Entry fields in a certain location
entry6.grid(row=10, column=1) # ^
def calculate():
if count == 2:
item_two()
output()
else:
item_three()
output()
def output(): #defines the custom command which calculates prices and quantities
print("Price 1: %s\nQuantity of Item 1: %s" % (entry1.get(), entry2.get())) #Debugging
print("Price 2: %s\nQuantity of Item 2: %s" % (entry3.get(), entry4.get())) #Debugging
print(m.get())
def item_two():
a = entry1.get() #Gets value from the entry fields
ap = entry2.get()
b = entry3.get()
bp = entry4.get()
aa = float(a)/float(ap) #Calcultes Price per item/ quantity of item 1
ba = float(b)/float(bp) #Calculates price per item/quantity of item 2
if aa == ba: #Finds which one is better
print('They are the same value') #Outputs value in output
r = ('They are the same value') #Sets Value to R
else:
if aa > ba:
print('The second item is better value') #^
r = ('The second item is better value') #Sets Value to R
else:
if ba > aa:
print('The first item is better value') #^
r = ('The first item is better value') #Sets Value to R
else:
r = ('Malfunction Occured Please check the input Values')
messagebox.showinfo("Best buy", r) #Creates a message box with pops up which shows r (result)
def item_three():
a = entry1.get() #Gets value from the entry fields
ap = entry2.get()
b = entry3.get()
bp = entry4.get()
c = entry5.get()
cp = entry6.get()
aa = float(a)/float(ap) #Calcultes Price per item/ quantity of item 1
ba = float(b)/float(bp) #Calculates price per item/quantity of item 2
c = int(c)
cp = int(cp)
ca = int(ca)
ca = float(c)/float(cp)
item_three()
if aa == ba and ba == ca:
r = ('They are all the same value')
elif aa == ba and ca > aa:
r = ('Item 1 and 2 are the best value')
elif aa == ca and ba > aa:
r = ('Item 1 and 3 are the best value')
elif ba == ca and aa > ba:
r = ('Item 1 and 3 are the best value')
messagebox.showinfo("Best buy", r) #Creates a message box with pops up which shows r (result)
def checkvar(var):
try:
var = int(var)
num = ('True')
except ValueError:
messagebox.showinfo("Best buy", "PLease Enter a Valid Number")
Label(master, text="Best Buy Calculator", font=("Helvetica", 20, "bold underline")).grid(row=0)
Label(master, text="Item #1", font=("Helvetica", 17, "bold underline")).grid(row=2) #1st Item Fields
Label(master, textvariable=c).grid(row=3)
Label(master, textvariable=m).grid(row=4)
entry1 = Entry(master) #Entry Feilds
entry2 = Entry(master)
entry1.grid(row=3, column=1) #Puts Entry fields in a certain location
entry2.grid(row=4, column=1) # ^
Label(master, text="Item #2", font=("Helvetica", 17, "bold underline")).grid(row=5) #2nd Item Fields
Label(master, textvariable=c).grid(row=6)
Label(master, textvariable=m).grid(row=7)
entry3 = Entry(master) #Entry Feilds (Variables)
entry4 = Entry(master)
entry3.grid(row=6, column=1) #2nd Item Entry fields
entry4.grid(row=7, column=1)
Button(master, text='+', command=addnew).grid(row=12, column=0, sticky=W, pady=4) #Cancel Button
Button(master, text='Cancel', command=quit).grid(row=13, column=0, sticky=W, pady=4) #Cancel Button
Button(master, text='Find Better Value', command=calculate).grid(row=13, column=1, sticky=W, pady=4) #Button to calculate better value
m.set("Measurement") # This is what the drop down box shows when no options are selected
c.set('Currency')
mes = OptionMenu(master, m, "Weight (kg)","Weight (g)", "Volume (mL)", "Quantity").grid(row=1) #Options and grid placement of the option menu
cur = OptionMenu(master, c, "AUD ($)","USD ($)", "EUR (€)", "GBP (£)", "CNY (¥)").grid(row=1, column=1) #Options and grid placement of the option menu
mainloop() #This is where the python code stops
提前致谢!
解决方案
entry5 和 entry6 总是返回一个空字符串,这就是你遇到这个问题的原因。
它给了你这个,因为你是在一个函数中创建这些条目,那些你是在那个函数中本地创建它们的。
我解决了你的问题
def addnew():
global count, entry5, entry6
在 addnew 中添加entry5
和entry6
到全局变量,当您在 item_three() 函数中使用 .get() 时,它将指向正确的地址
您还有其他问题,请从您的item_three
函数中删除此行:
ca = int(ca)
和
item_three() # this recurssion has no stoping condition
你也应该在这个函数中初始化 r 字符串:
r = ''
在你比较之前
这是我所做的:
from tkinter import * #Import the Tkinter module
from tkinter import messagebox #Imports the message box module
from tkinter import font #Imports fonts from tkinter
import json #Imports JSON
a = ('') #Variable for price and quantity/mass
b = ('') #^
c = ('') #^
d = ('') #^
e = ('') #^
f = ('') #^h
r = ('') #Result Var
aa = ('')
ba = ('')
ca = ('')
c = 1
cp = 1
ca = 1
count = 2 #For extra Fields
master = Tk() #Tkinter
m = StringVar(master) #Defines m as yhe variable from the option menu
c = StringVar(master) #Defines m as yhe variable from the option menu
entry5 = Entry(master) #Entry Feilds (Variables)
entry6 = Entry(master)
def addnew():
global count, entry5, entry6
count = count+1
if count == 3:
Label(master, text="Item #3", font=("Helvetica", 17, "bold underline")).grid(row=8) #2nd Item Fields
Label(master, textvariable=c).grid(row=9)
Label(master, textvariable=m).grid(row=10)
entry5 = Entry(master) #Entry Feilds (Variables)
entry6 = Entry(master)
entry5.grid(row=9, column=1) #Puts Entry fields in a certain location
entry6.grid(row=10, column=1) # ^
#print(" en 5 id : {}".format(id(entry5)))
def calculate():
if count == 2:
item_two()
output()
else:
item_three()
output()
def output(): #defines the custom command which calculates prices and quantities
print("Price 1: %s\nQuantity of Item 1: %s" % (entry1.get(), entry2.get())) #Debugging
print("Price 2: %s\nQuantity of Item 2: %s" % (entry3.get(), entry4.get())) #Debugging
print(m.get())
def item_two():
a = entry1.get() #Gets value from the entry fields
ap = entry2.get()
b = entry3.get()
bp = entry4.get()
aa = float(a)/float(ap) #Calcultes Price per item/ quantity of item 1
ba = float(b)/float(bp) #Calculates price per item/quantity of item 2
if aa == ba: #Finds which one is better
print('They are the same value') #Outputs value in output
r = ('They are the same value') #Sets Value to R
else:
if aa > ba:
print('The second item is better value') #^
r = ('The second item is better value') #Sets Value to R
else:
if ba > aa:
print('The first item is better value') #^
r = ('The first item is better value') #Sets Value to R
else:
r = ('Malfunction Occured Please check the input Values')
messagebox.showinfo("Best buy", r) #Creates a message box with pops up which shows r (result)
def item_three():
a = entry1.get() #Gets value from the entry fields
ap = entry2.get()
b = entry3.get()
bp = entry4.get()
c = entry5.get()
cp = entry6.get()
aa = float(a)/float(ap) #Calcultes Price per item/ quantity of item 1
ba = float(b)/float(bp) #Calculates price per item/quantity of item 2
#print(" en 1 id : {}".format(id(entry1)))
#print(" en 5 id : {}".format(id(entry5)))
c = float(c)
cp = float(cp)
#ca = float(ca)
ca = float(c)/float(cp)
#item_three()
r = ''
if aa == ba and ba == ca:
r = ('They are all the same value')
elif aa == ba and ca > aa:
r = ('Item 1 and 2 are the best value')
elif aa == ca and ba > aa:
r = ('Item 1 and 3 are the best value')
elif ba == ca and aa > ba:
r = ('Item 1 and 3 are the best value')
messagebox.showinfo("Best buy", r) #Creates a message box with pops up which shows r (result)
def checkvar(var):
try:
var = int(var)
num = ('True')
except ValueError:
messagebox.showinfo("Best buy", "PLease Enter a Valid Number")
Label(master, text="Best Buy Calculator", font=("Helvetica", 20, "bold underline")).grid(row=0)
Label(master, text="Item #1", font=("Helvetica", 17, "bold underline")).grid(row=2) #1st Item Fields
Label(master, textvariable=c).grid(row=3)
Label(master, textvariable=m).grid(row=4)
entry1 = Entry(master) #Entry Feilds
entry2 = Entry(master)
entry1.grid(row=3, column=1) #Puts Entry fields in a certain location
entry2.grid(row=4, column=1) # ^
#print(" en 1 id : {}".format(id(entry1)))
Label(master, text="Item #2", font=("Helvetica", 17, "bold underline")).grid(row=5) #2nd Item Fields
Label(master, textvariable=c).grid(row=6)
Label(master, textvariable=m).grid(row=7)
entry3 = Entry(master) #Entry Feilds (Variables)
entry4 = Entry(master)
entry3.grid(row=6, column=1) #2nd Item Entry fields
entry4.grid(row=7, column=1)
Button(master, text='+', command=addnew).grid(row=12, column=0, sticky=W, pady=4) #Cancel Button
Button(master, text='Cancel', command=quit).grid(row=13, column=0, sticky=W, pady=4) #Cancel Button
Button(master, text='Find Better Value', command=calculate).grid(row=13, column=1, sticky=W, pady=4) #Button to calculate better value
m.set("Measurement") # This is what the drop down box shows when no options are selected
c.set('Currency')
mes = OptionMenu(master, m, "Weight (kg)","Weight (g)", "Volume (mL)", "Quantity").grid(row=1) #Options and grid placement of the option menu
cur = OptionMenu(master, c, "AUD ($)","USD ($)", "EUR ()", "GBP ()", "CNY ()").grid(row=1, column=1) #Options and grid placement of the option menu
mainloop()
推荐阅读
- php - 在Mysql中选择日期返回错误的数据
- mysql - 无法使用 My Ip 连接到 AWS RDS,但可以使用 Anywhere
- javascript - Angular:从没有事件的孩子那里获取数据
- haskell - 如何为 Cabal/Stack 包指定源文件,而不仅仅是 hs-source-dirs/source-dirs?
- javascript - 将日期时间从 axios 数据 (YYYY-DD-MMThh:mm:ss) 转换为 MM/DD/YY
- dart - 如何在颤动中将数据从警报对话框传递到同一页面
- python - 在 Power BI 中使用 Python 脚本,ImportError: Missing required dependencies ['numpy']
- stdout - 为什么 `ssh-keygen --help` 不进入标准输出?
- c# - 有人可以解释这个类(它产生一个可以改变的正弦波频率)是如何工作的吗?
- google-maps - 使用 HERE 或 Google Maps API 检索沿线的所有状态