【问题标题】:Problems with Integer and Floats with PythonPython 的整数和浮点数问题
【发布时间】:2023-03-28 13:50:01
【问题描述】:

在过去的几个月里,我一直在制作一个代码,可以从条目中找到最便宜的产品。 一切正常,直到我按下加号按钮添加新项目。填写完这些字段后,我得到了一个带有错误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

提前致谢!

【问题讨论】:

    标签: python string tkinter int


    【解决方案1】:

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

    它告诉你,因为你是在一个函数中创建这些条目,你是在那个函数中本地创建它们。

    我解决了你的问题,

    def addnew():
       global count, entry5, entry6
    

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

    【讨论】:

      猜你喜欢
      • 2017-07-26
      • 2020-08-24
      • 1970-01-01
      • 2020-11-30
      • 1970-01-01
      • 2020-07-26
      • 2011-01-04
      • 1970-01-01
      • 2011-01-10
      相关资源
      最近更新 更多