所以我目前正在制作GUI计算器,但我不确定如何编写将执行计算器操作的代码。现在我目前已经设置了窗口,输入框和计算器按钮,但目前它们都没有做任何事情。
我对如何在代码中表示这些按钮感到困惑,因此我不确定如何编写能够读取这些按钮输入并执行加法,减法等的代码块。
到目前为止,这是我的代码
class Calculator(Frame):
def __init__(self,master):
Frame.__init__(self,master)
self.grid()
self.dataEnt = Entry(self)
self.dataEnt.grid(row = 0, column = 1, columnspan = 4)
labels =[['AC','%','/'],
['7','8','9','*'],
['4','5','6','-'],
['1','2','3','+'],
['0','.','=']]
label = Button(self,relief = RAISED, padx = 10, text = labels[0][0]) #AC
label.grid(row = 1, column = 0, columnspan = 2)
label = Button(self,relief = RAISED, padx = 10, text = labels[0][1]) # %
label.grid(row = 1, column = 3)
label = Button(self,relief = RAISED, padx = 10, text = labels[0][2]) # /
label.grid(row = 1, column = 4)
for r in range(1,4):
for c in range(4):
#create label for row r and column c
label = Button(self,relief = RAISED,
padx = 10,
text = labels[r][c]) # 789* 456- 123+
# place label in row r and column c
label.grid(row = r+1, column = c+1)
label = Button(self,relief = RAISED, padx = 10, text = labels[4][0]) #0
label.grid(row = 5, column = 0, columnspan = 2)
label = Button(self,relief = RAISED, padx = 10, text = labels[4][1]) # .
label.grid(row = 5, column = 3)
label = Button(self,relief = RAISED, padx = 10, text = labels[4][2]) # =
label.grid(row = 5, column = 4)
def operations(self,num ):
def main():
root = Tk()
root.title('Calculator')
obj = Calculator(root)
root.mainloop()
and here is what the calculator looks like so far
我的猜测是我需要能够以某种方式将输入作为字符串读取然后让python将该字符串作为数学表达式进行评估,但我不确定如何去做。
感谢您的帮助!
答案 0 :(得分:0)
您可以做的是绑定所有按钮到标识按钮的方法,并将字符串附加到列表或评估表达式。然后可以在标签中显示该列表。
def button_press(self, event):
widget = event.widget
text = widget["text"]
if text != "AC" and text != "=":
self.operations.append(text)
elif text == "AC":
self.operations = [] # Clear the list.
elif text == "=":
self.evaluate()
self.label["text"] = "".join(self.operations)
def evaluate(self):
try:
self.operations = [str(eval("".join(self.operations)))]
except (ArithmeticError, SyntaxError, TypeError, NameError):
self.operations = ["ERROR"]
此代码不能只是粘贴到您的程序中,而只是为了演示如何解决问题。