Python的整数和浮点问题

2024-03-28 22:28:39 发布

您现在位置: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,我也会把代码放在下面 复制链接: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

提前谢谢!你知道吗


Tags: andthemastergetvaluefloatitemlabel
1条回答
网友
1楼 · 发布于 2024-03-28 22:28:39

entry5和entry6总是返回一个空字符串,这就是为什么会出现这个问题。你知道吗

因为你在一个函数中创建这些条目,所以你在这个函数中本地创建它们。你知道吗

我解决了你的问题

def addnew():
   global count, entry5, entry6

entry5entry6添加到addnew中的全局变量中,当您在item\u 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()

相关问题 更多 >