【问题标题】:Why I get errors when I run my calculation buttons using Python Tkinter?为什么我在使用 Python Tkinter 运行计算按钮时会出错?
【发布时间】:2015-05-31 07:01:08
【问题描述】:

这是我目前的代码:

#Calculator
from Tkinter import*

class Calculator():
    def __init__ (self):
        self.total = 0
        self.current = ""
        self.newnumber = True
        self.operation1 = ""
        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.operation1_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.operation1 == "subtract":
            self.total -= self.current
        if self.operation1 == "add":
            self.total += self.current
        if self.operation1 == "divide":
            self.total /= self.current
        if self.operation1 == "multiply":
            self.total *= self.current
        self.newnumber = True
        self.operation1_pending = False
        self.Display(self.total)

    def operation(self, operation1):
        self.current = float(self.current)
        if self.operation1_pending:
            self.calc_sum()
        elif not self.equal:
            self.total = self.current
        self.newnumber = True
        self.operation1_pending = True
        self.operation1 = 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["co`enter code here`mmand"] = summ.TotalCalculated
equals.grid(row = 5, column = 3, pady = 10)

root.mainloop()

最初有人建议我更改 self.operation 和 def operation 的名称,我已经做到了。但是,它给了我另一个错误。

如果有人能告诉我正确的代码,那将对我有很大帮助。 这是我按下其中一个计算按钮时收到的错误消息:

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")
  File "C:\Users\HANY\Documents\Nona CS\Calculator3.py", line 52, in operation
    if self.operation1_pending:
AttributeError: Calculator instance has no attribute 'operation1_pending'

谢谢!!

【问题讨论】:

  • 自我。 operation1_pending 仅在部分方法中定义,__init__ 方法中没有定义,所以它的存在取决于您之前是否调用过这些方法。在这种情况下,你没猜到
  • 只需添加自我。 operation1_pending = False in __init__
  • @JulienSpronc 只需回答一下,我们就可以投票了。你似乎是对的。

标签: python tkinter calculator


【解决方案1】:

self. operation1_pending只在部分方法中定义,__init__()方法中没有定义,所以它的存在取决于你之前是否调用过这些方法。在这种情况下,您可能没有。

只需在__init__() 中添加self. operation1_pending = False

作为一般规则,通常最好在__init__() 方法中定义所有实例变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多