[英]Converting an Empty String to Float
so I found a calculator I created a few years ago in Python and I decided to run it but it isn't working anymore.所以我在 Python 找到了我几年前创建的计算器,我决定运行它,但它不再工作了。 I am trying to fix it because I want to get back into programming.
我正在尝试修复它,因为我想重新开始编程。
Here is some of my code from the program:这是我的程序中的一些代码:
from tkinter import *
master = Tk()
display = Entry(master, width=15, justify="right", bd=0, bg="lightgrey")
master.title("Calculator")
class Calculator:
def __init__(self): # the method called when we create our calculator method
self.var1="" # first variable of the calculator
self.var2=""
self.result=0 # the result of the last equation
self.current=0 # the current variable ur on
self.operator=0 # the number of the operator
def numb_butt(self, index): # will take index as a parameter and add it to the proper variable
if self.current == 0:
self.var1 = str(self.var1) + str(index)
display.delete(0, END)
display.insert(0, string=self.var1)
else:
self.var2 = str(self.var2) + str(index)
display.delete(0, END)
display.insert(0, string=self.var2)
def equate(self): # find out what operator we're using and add, subtract, etc
if self.operator == 0:
self.result = float(self.var1) + float(self.var2)
elif self.operator == 1:
self.result = float(self.var1) - float(self.var2)
elif self.operator == 2:
self.result = float(self.var1)* float(self.var2)
elif self.operator == 3:
self.result = float(self.var1) / float(self.var2)
display.delete(0, END)
display.insert(0, string=self.result)
I keep getting this error:我不断收到此错误:
return self.func(*args)
File "calculator.py", line 33, in equate
self.result = float(self.var1)* float(self.var2)
ValueError: could not convert string to float: ''
It doesn't solely happen with multiplication, it is now happening with all operations它不仅仅发生在乘法上,它现在发生在所有操作中
Why not just init var1 & var2 as floats from the beginning instead of strings?为什么不从一开始就将 var1 和 var2 初始化为浮点数而不是字符串?
var1 = float(0)
var2 = float(0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.