帮我完善以下代码from tkinter import *#计算器 from tkinter import messagebox import random class Application(Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.pack() self.createWidget() def createWidget(self): """通过 grid 布局实现计算器的界面""" btnText = (("MC","M+","M-","MR"), ("C","±","/","✖ "), (7,8,9,"-"), (4,5,6,"+"), (1,2,3,"="), (0,".")) Entry(self).grid(row=0,column=0,columnspan=4,pady=10) for rindex,r in enumerate(btnText): for cindex,c in enumerate(r): if c == "=": Button(self,text=c,width=2)\ .grid(row=rindex+1,column=cindex,rowspan=2,sticky=NSEW) elif c == 0: Button(self, text=c, width=2) \ .grid(row=rindex + 1, column=cindex, columnspan = 2, sticky = NSEW) elif c == ".": Button(self, text=c, width=2) \ .grid(row=rindex + 1, column=cindex + 1, sticky = NSEW) else: Button(self, text=c, width=2) \ .grid(row=rindex + 1, column=cindex, sticky=NSEW) if __name__ == '__main__': root = Tk() root.geometry("250x250+200+300") app = Application(master=root) root.mainloop()
时间: 2023-12-15 10:03:30 浏览: 121
以下是一个简单的计算器功能实现,可以将其添加到 createWidget() 方法中:
```python
def calculate(self, expression):
"""计算表达式"""
try:
result = eval(expression)
self.entry.delete(0, END)
self.entry.insert(0, result)
except:
messagebox.showerror("Error", "表达式有误!")
def press(self, text):
"""按下按钮时的事件响应"""
if text == "=":
expression = self.entry.get()
self.calculate(expression)
elif text == "C":
self.entry.delete(0, END)
elif text == "±":
expression = self.entry.get()
if expression.startswith("-"):
self.entry.delete(0)
self.entry.insert(0, expression[1:])
else:
self.entry.insert(0, "-")
else:
self.entry.insert(END, text)
def createWidget(self):
"""通过 grid 布局实现计算器的界面"""
self.entry = Entry(self)
self.entry.grid(row=0, column=0, columnspan=4, pady=10)
btnText = (("MC", "M+", "M-", "MR"),
("C", "±", "/", "✖ "),
(7, 8, 9, "-"),
(4, 5, 6, "+"),
(1, 2, 3, "="),
(0, "."))
for rindex, r in enumerate(btnText):
for cindex, c in enumerate(r):
if c == "=":
Button(self, text=c, width=2, command=lambda: self.press(c)) \
.grid(row=rindex + 1, column=cindex, rowspan=2, sticky=NSEW)
elif c == 0:
Button(self, text=c, width=2, command=lambda: self.press(c)) \
.grid(row=rindex + 1, column=cindex, columnspan=2, sticky=NSEW)
elif c == ".":
Button(self, text=c, width=2, command=lambda: self.press(c)) \
.grid(row=rindex + 1, column=cindex + 1, sticky=NSEW)
else:
Button(self, text=c, width=2, command=lambda x=c: self.press(x)) \
.grid(row=rindex + 1, column=cindex, sticky=NSEW)
```
其中,我们添加了 calculate() 方法用于计算表达式,并在按下 "=" 按钮时调用。同时,我们将 Entry 对象保存在类属性中,以便在 press() 方法中使用。press() 方法用于处理按钮的事件响应,当按下 "=" 按钮时,获取当前表达式并传递给 calculate() 方法计算结果;当按下 "C" 按钮时,清除输入框;当按下 "±" 按钮时,将表达式取反。在 createWidget() 方法中,我们为每个按钮添加相应的事件响应函数。
阅读全文