Проблемы с Integer и Floats с Python - PullRequest
0 голосов
/ 13 мая 2019

За последние несколько месяцев я делал код, который находит самый дешевый продукт из записей. Все работает до тех пор, пока я не нажму кнопку «плюс», чтобы добавить новый элемент. После заполнения полей мне выдается вывод с ошибкой 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

Заранее спасибо!

1 Ответ

0 голосов
/ 13 мая 2019

entry5 и entry6 всегда возвращают пустую строку, поэтому вы получаете эту проблему.

и это дает вам понять, что, поскольку вы создаете эти записи внутри функции, те, которые вы создаете в них локально.

Я решил твою проблему,

def addnew():
   global count, entry5, entry6

добавьте entry5 и entry6 к глобальным переменным в addnew, когда вы используете .get () в своей функции item_three (), он будет указывать на правильный адрес

У вас также есть другие проблемы, удалите эти строки из вашей 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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...