Python的整数和浮点运算问题

时间:2019-05-13 10:07:19

标签: python string tkinter int

在过去的几个月中,我一直在编写代码,以从条目中查找最便宜的产品。 一切正常,直到我按下加号按钮添加新项目为止。填写完字段后,输出为错误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

谢谢!

1 个答案:

答案 0 :(得分:0)

entry5和entry6始终返回一个空字符串,这就是您遇到此问题的原因。

它给您的是,因为您是在函数内创建这些条目,所以您正在该函数中本地创建这些条目。

我解决了您的问题,

def addnew():
   global count, entry5, entry6

entry5entry6添加到a​​ddnew的全局变量中,当您在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()