python实现tkinter简易计算器的实现
时间: 2023-10-31 21:05:39 浏览: 244
下面是一个简易的计算器的Python tkinter实现代码:
```python
import tkinter as tk
class Calculator:
def __init__(self, master):
self.master = master
master.title("Calculator")
# 创建显示框
self.display = tk.Entry(master, width=32, font=('Arial', 16))
self.display.grid(row=0, column=0, columnspan=4, padx=5, pady=5)
# 创建按钮
self.button_1 = tk.Button(master, text="1", command=lambda: self.button_click(1))
self.button_2 = tk.Button(master, text="2", command=lambda: self.button_click(2))
self.button_3 = tk.Button(master, text="3", command=lambda: self.button_click(3))
self.button_4 = tk.Button(master, text="4", command=lambda: self.button_click(4))
self.button_5 = tk.Button(master, text="5", command=lambda: self.button_click(5))
self.button_6 = tk.Button(master, text="6", command=lambda: self.button_click(6))
self.button_7 = tk.Button(master, text="7", command=lambda: self.button_click(7))
self.button_8 = tk.Button(master, text="8", command=lambda: self.button_click(8))
self.button_9 = tk.Button(master, text="9", command=lambda: self.button_click(9))
self.button_0 = tk.Button(master, text="0", command=lambda: self.button_click(0))
self.button_add = tk.Button(master, text="+", command=lambda: self.operation_click('+'))
self.button_subtract = tk.Button(master, text="-", command=lambda: self.operation_click('-'))
self.button_multiply = tk.Button(master, text="*", command=lambda: self.operation_click('*'))
self.button_divide = tk.Button(master, text="/", command=lambda: self.operation_click('/'))
self.button_equal = tk.Button(master, text="=", command=self.calculate)
self.button_clear = tk.Button(master, text="C", command=self.clear_display)
# 布置按钮
self.button_1.grid(row=1, column=0)
self.button_2.grid(row=1, column=1)
self.button_3.grid(row=1, column=2)
self.button_add.grid(row=1, column=3)
self.button_4.grid(row=2, column=0)
self.button_5.grid(row=2, column=1)
self.button_6.grid(row=2, column=2)
self.button_subtract.grid(row=2, column=3)
self.button_7.grid(row=3, column=0)
self.button_8.grid(row=3, column=1)
self.button_9.grid(row=3, column=2)
self.button_multiply.grid(row=3, column=3)
self.button_clear.grid(row=4, column=0)
self.button_0.grid(row=4, column=1)
self.button_equal.grid(row=4, column=2)
self.button_divide.grid(row=4, column=3)
def button_click(self, number):
current = self.display.get()
self.display.delete(0, tk.END)
self.display.insert(0, str(current) + str(number))
def operation_click(self, operator):
current = self.display.get()
self.display.delete(0, tk.END)
self.display.insert(0, str(current) + operator)
def calculate(self):
current = self.display.get()
self.display.delete(0, tk.END)
try:
self.display.insert(0, eval(current))
except:
self.display.insert(0, "Error")
def clear_display(self):
self.display.delete(0, tk.END)
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()
```
这个计算器实现了基本的加减乘除与括号功能。你可以根据需求进行拓展。
阅读全文