python实现tkinter简易计算器的实现
时间: 2023-10-31 21:05:55 浏览: 91
以下是一个简单的基于Tkinter实现的计算器:
```python
import tkinter as tk
class Calculator(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.createWidgets()
def createWidgets(self):
# 显示器
self.display = tk.Entry(self, font=('Helvetica', 16), width=18, justify='right')
self.display.grid(row=0, column=0, columnspan=4, padx=8, pady=8)
# 数字键
digits = [
'7', '8', '9',
'4', '5', '6',
'1', '2', '3',
'0', '.', '='
]
r = 1
c = 0
for d in digits:
btn = tk.Button(self, text=d, font=('Helvetica', 16), width=4, height=2,
command=lambda x=d: self.onClick(x))
btn.grid(row=r, column=c, padx=2, pady=2)
c += 1
if c > 2:
c = 0
r += 1
# 运算符键
ops = [
'+', '-', '*', '/',
'(', ')', 'C', 'AC'
]
r = 1
c = 3
for o in ops:
btn = tk.Button(self, text=o, font=('Helvetica', 16), width=4, height=2,
command=lambda x=o: self.onClick(x))
btn.grid(row=r, column=c, padx=2, pady=2)
r += 1
if r > 5:
r = 1
c += 1
def onClick(self, key):
if key == '=':
try:
result = str(eval(self.display.get()))
except:
result = 'Error'
self.display.delete(0, tk.END)
self.display.insert(tk.END, result)
elif key == 'C':
self.display.delete(len(self.display.get())-1, tk.END)
elif key == 'AC':
self.display.delete(0, tk.END)
else:
self.display.insert(tk.END, key)
if __name__ == '__main__':
root = tk.Tk()
root.title('Calculator')
app = Calculator(master=root)
app.mainloop()
```
运行上述代码,即可在窗口中看到一个简单的计算器界面。该计算器支持数字、小数点、加减乘除、左右括号、清除、全部清除等操作,并且可以计算出表达式的结果。
阅读全文