作为我自学python'的一部分,我目前正在创建一个GUI计算器。到目前为止,我已经启动并运行了界面。然而,当我重用计算器(没有重新启动应用程序)时,一个操作是可用的,我得到一个" TypeError:' str'对象不可调用",这表明我没有使用代码。有人可以提供一些有用的指示吗?非常感谢。
def create_widgets(self):
"""Create buttons, text and entry widgets"""
# Create a text widget
self.txt = Text(self, width = 40, height = 1, wrap = NONE, pady = 10)
self.txt.grid(row = 0, column = 0, columnspan = 4)
# Create number 1
self.btn1 = Button(self, text = "1", command = lambda: self.insert_number(1), width = 10, pady = 10)
self.btn1.grid(row = 1, column = 0, columnspan = 1, sticky = W)
# Create number 2
self.btn2 = Button(self, text = "2", command = lambda: self.insert_number(2), width = 10, pady = 10)
self.btn2.grid(row = 1, column = 1, columnspan = 1, sticky = W)
# Create minus button
self.btn_minus = Button(self, text = "-", command = lambda: self.operator("-"), width = 10, pady = 10)
self.btn_minus.grid(row = 1, column = 3, columnspan = 1, sticky = W)
# Create clear button
self.btn_clear = Button(self, text = "C", command = self.clear, width = 10, pady = 10)
self.btn_clear.grid(row = 4, column = 0, columnspan = 1, sticky = W)
# Create equals
self.btn_equals = Button(self, text = "=", command = self.equals, width = 10, pady = 10)
self.btn_equals.grid(row = 4, column = 2, columnspan = 1, sticky = W)
def insert_number(self, number):
"""insert number to the calculator"""
self.txt.insert(END, number)
def operator(self, action):
"""Make an addition, subtraction, division or multiplication"""
self.first_number = self.txt.get(0.0, END)
self.txt.delete(0.0, END)
self.operator = action
def equals(self):
self.second_number = self.txt.get(0.0, END)
self.txt.delete(0.0, END)
if self.operator == "-": # If operator is minus
self.answer = int(self.first_number) - int(self.second_number)
self.txt.insert(0.0, self.answer)
def clear(self):
self.txt.delete(0.0, END)
按下'减号&#39>时出现错误信息按钮第二次:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "C:\Users\Dan\Documents\Coding\Python Projects\Book\calculator.py", line 33, in <lambda>
self.btn_minus = Button(self, text = "-", command = lambda: self.operator("-"), width = 10, pady = 10)
TypeError: 'str' object is not callable
答案 0 :(得分:1)
您的错误在于:self.operator = action
基本上,您将self.operator的值从方法设置为字符串,因此当您调用self.operator('-')
时,您尝试执行' - '并获取TypeError。我建议将self.operator = action
更改为
global operator
operator = action
并将if self.operator == "-":
替换为if operator == "-":