2015-03-27 2 views
1
#Calculator codes 
from Tkinter import* 

class Calculator(): 
    def __init__ (self): 
     self.total = 0 
     self.current = "" 
     self.newnumber = True 
     self.operation = "" 
     self.equal = False 

    def PressedNumber(self, number): 
     self.equal = False 
     t = text_box.get() 
     n = str(number) 
     if self.newnumber: 
      self.current = n 
      self.newnumber = False 
     else: 
      if n == '.': 
       if n in t: 
        return 
       self.current = t + n 
     self.Display(self.current) 

    def TotalCalculated(self): 
     self.equal = True 
     self.current = float(self.current) 
     if self.operation_pending == True: 
      self.calc_sum() 
     else: 
      self.total = float(text_box.get()) 

    def Display(self, value): 
     text_box.delete(0, END) 
     text_box.insert(0, value) 

    def calc_sum(self): 
     if self.operation == "subtract": 
      self.total -= self.current 
     if self.operation == "add": 
      self.total += self.current 
     if self.operation == "divide": 
      self.total /= self.current 
     if self.operation == "multiply": 
      self.total *= self.current 
     self.newnumber = True 
     self.operation_pending = False 
     self.Display(self.total) 

    def operation(self, operation): 
     self.current = float(self.current) 
     if self.operation_pending: 
      self.calc_sum() 
     elif not self.equal: 
      self.total = self.current 
     self.newnumber = True 
     self.operation_pending = True 
     self.operation = operation 
     self.equal = False 

    def cancel(self): 
     self.equal = False 
     self.current = "0" 
     self.Display(0) 
     self.newnumber = True 

    def Cancelation_forEverything(self): 
     self.cancel() 
     self.total = 0 

    def sign(self): 
     self.equal = False 
     self.current = -(float(text_box.get())) 
     self.Display(self.current) 

summ = Calculator() 
root = Tk() 
Calculator = Frame(root) 
Calculator.grid() 

root.title("Calculator") 
root.configure(bg="Khaki") 
root.minsize(width=220, height=20) 
root.resizable(width=FALSE, height= FALSE) 
text_box = Entry(Calculator, justify=RIGHT) 
text_box.grid(row = 0, column = 0, columnspan=3, pady = 8, sticky=W+E) 
text_box.insert(0, "0") 

Numbers = "789456123" 
a = 0 
bttn = [] 
for r in range(1,4): 
    for c in range(3): 
     bttn.append(Button(Calculator, text = Numbers[a], font="Candara,20")) 
     bttn[a].grid(row = r, column = c, padx= 15, pady = 15) 
     bttn[a]["command"] = lambda x = Numbers[a]: summ.PressedNumber(x) 
     a += 1 

bttn_0 = Button(Calculator, text = "  0  ", font="Candara,20") 
bttn_0["command"] = lambda: summ.PressedNumber(0) 
bttn_0.grid(columnspan = 5, sticky=N+W, padx= 20, pady = 20) 

bttn_division = Button(Calculator, text = chr(247), font="Candara,20") 
bttn_division["command"] = lambda: summ.operation("divide") 
bttn_division.grid(row = 1, column = 3, pady = 10) 

bttn_multiply = Button(Calculator, text = "x", font="Candara,20") 
bttn_multiply["command"] = lambda: summ.operation("multiply") 
bttn_multiply.grid(row = 2, column = 3, sticky=N, pady = 10) 

bttn_subtract = Button(Calculator, text = "-", font="Candara,20") 
bttn_subtract["command"] = lambda: summ.operation("subtract") 
bttn_subtract.grid(row = 3, column = 3, pady = 10) 

bttn_point = Button(Calculator, text = ".", font="Candara,20") 
bttn_point["command"] = lambda: summ.PressedNumber(".") 
bttn_point.grid(row = 4, column = 1, padx = 10, pady = 10) 

bttn_addition = Button(Calculator, text = "+", font="Candara,20") 
bttn_addition["command"] = lambda: summ.operation("add") 
bttn_addition.grid(row = 4, column = 3, pady = 10) 

bttn_neg = Button(Calculator, text = "+/-", font="Candara,20") 
bttn_neg["command"] = summ.sign 
bttn_neg.grid(row = 5, column = 0, pady = 10) 

clear = Button(Calculator, text = "C", font="Candara,20") 
clear["command"] = summ.cancel 
clear.grid(row = 5, column = 1, pady = 10) 

all_clear = Button(Calculator, text = "AC", font="Candara,20") 
all_clear["command"] = summ.Cancelation_forEverything 
all_clear.grid(row = 5, column = 2, pady = 10) 

equals = Button(Calculator, text = "=", font="Candara,20") 
equals["command"] = summ.TotalCalculated 
equals.grid(row = 5, column = 3, pady = 10) 

root.mainloop() 

После того, как я добавить цветовые коды, вычислительные знаки не хотят работать и получить мне ошибку ... Вот сообщение об ошибке, когда я нажимаю один из счетных признаков:Почему мои кнопки не работают для калькулятора Tkinter?

Exception in Tkinter callback 
Traceback (most recent call last): 
    File "C:\Python27\lib\lib-tk\Tkinter.py", line 1532, in __call__ 
    return self.func(*args) 
    File "C:\Users\HANY\Documents\Nona CS\Calculator3.py", line 108, in <lambda> 
    bttn_multiply["command"] = lambda: summ.operation("multiply") 
TypeError: 'str' object is not callable 

Может кто-нибудь, пожалуйста, скажите мне, что делать, чтобы коды работали?

ответ

4

Я думаю, что проблема в том, что в вас Калькулятор класса вы определяете operation в качестве переменной строки:

self.operation = "" 

Но тогда вы также определить его как метод:

def operation(self, operation) 

Таким образом, когда вы summ.operation("multiply") python вызывает строковую переменную, а не метод. Который, конечно, приводит к ошибке, что строки не подлежат вызову.

+0

то что вы предлагаете исправить в коде для того, чтобы работать? – Naity

+1

Не пытайтесь дать две разные вещи с тем же именем ... – kindall

+0

@kindall Спасибо! – Naity

Смежные вопросы