-1

I am trying to program a calculator using python. It does not let me run the code because this error tells that: ValueError: could not convert string to float: '' This code was working but suddenly this error showed up. Could anyone help me with telling what I should change or add. This is the part of the code where the error occurs.

def operation(self, op):
    self.current = float(self.current)
    if self.check_sum:
        self.valid_function()
    elif not self.result:
        self.total = self.current
        self.input_value = True
    self.check_sum = True
    self.op = op
    self.result = False

2 Answers2

0

The problem is here:

added_value = Calc

This doesn't create a new class instance. It merely assigns the class itself to added_value. Change it to:

added_value = Calc()

This will create a new class instance, so added_value.numberEnter will be a bound method.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
0

You forgot to instantiate your Calc class.

added_value = Calc

must be changed to:

added_value = Calc()

Fully functional code (I tested):

from tkinter import *
import math


root = Tk()
root.title("Mathematical Calculator")
root.geometry("416x550+500+40")

calc = Frame(root, bd=20, pady=5, bg="gainsboro", relief=RIDGE)
calc.grid()

class Calc():
    def __init__(self):
        self.total = 0
        self.current = ""
        self.input_value = True
        self.check_sum = False
        self.op = ""
        self.result = False

    def numberEnter(self, num):
        self.result = False
        firstnum = txtDisplay.get()
        secondnum = str(num)
        if self.input_value:
            self.current = secondnum
            self.input_value = False
        else:
            if secondnum == '.':
                if secondnum in firstnum:
                    return
            self.current = firstnum + secondnum
        self.display(self.current)

    def display(self, value):
        txtDisplay.delete(0, END)
        txtDisplay.insert(0, value)


added_value = Calc()

txtDisplay = Entry(calc, font=("Courier New", 16, "bold"), bd=20, width=28, justify=RIGHT)
txtDisplay.grid(row=0, column=0, columnspan=4, pady=1)
txtDisplay.insert(0, "0")

numberpad = "789456123"
i = 0
btn = []

for j in range(3, 6):
    for k in range(3):
        btn.append(Button(calc, width=6, height=2

, font=("Courier New", 16, "bold"), bd=4, text=numberpad[i]))
        btn[i].grid(row=j, column=k, pady=1)
        btn[i]["command"] = lambda x = numberpad[i]: added_value.numberEnter(x)
        i += 1
    

root.mainloop()
Vu Tung Lam
  • 143
  • 1
  • 6