用python做一个计算器,第一行为文本框文字内容右对齐用来放计算器计算内容,第二行包含清空按钮ac和加号按钮其中ac占三列,第三行包含1,2,3和减号,第四行包含4,5,6和乘号,第五行包含7,8,9 和除号,第六行包含0和点和等号其中0占两列
时间: 2024-05-14 18:18:36 浏览: 47
python 简易计算器程序,代码就几行
5星 · 资源好评率100%
以下是用Python实现计算器的代码:
```python
import tkinter as tk
class Calculator:
def __init__(self, master):
self.master = master
master.title("Calculator")
# 创建文本框
self.display = tk.Entry(master, width=30, justify="right")
self.display.grid(row=0, column=0, columnspan=4, padx=5, pady=5)
# 创建按钮
self.create_button("AC", 1, 0, 3, self.clear)
self.create_button("+", 1, 3, self.add)
self.create_button("1", 2, 0, self.add_number, 1)
self.create_button("2", 2, 1, self.add_number, 2)
self.create_button("3", 2, 2, self.add_number, 3)
self.create_button("-", 2, 3, self.subtract)
self.create_button("4", 3, 0, self.add_number, 4)
self.create_button("5", 3, 1, self.add_number, 5)
self.create_button("6", 3, 2, self.add_number, 6)
self.create_button("*", 3, 3, self.multiply)
self.create_button("7", 4, 0, self.add_number, 7)
self.create_button("8", 4, 1, self.add_number, 8)
self.create_button("9", 4, 2, self.add_number, 9)
self.create_button("/", 4, 3, self.divide)
self.create_button("0", 5, 0, self.add_number, 0, columnspan=2)
self.create_button(".", 5, 2, self.add_decimal)
self.create_button("=", 5, 3, self.calculate)
def create_button(self, text, row, column, command=None, value=None, columnspan=1):
button = tk.Button(self.master, text=text, width=7, height=2, command=lambda: command(value) if value else command(), padx=5, pady=5)
button.grid(row=row, column=column, columnspan=columnspan, padx=5, pady=5)
def add_number(self, number):
current = self.display.get()
self.display.delete(0, tk.END)
self.display.insert(0, str(current) + str(number))
def add_decimal(self):
current = self.display.get()
if "." not in current:
self.display.delete(0, tk.END)
self.display.insert(0, str(current) + ".")
def clear(self):
self.display.delete(0, tk.END)
def add(self):
self.operator = "+"
self.first_number = float(self.display.get())
self.display.delete(0, tk.END)
def subtract(self):
self.operator = "-"
self.first_number = float(self.display.get())
self.display.delete(0, tk.END)
def multiply(self):
self.operator = "*"
self.first_number = float(self.display.get())
self.display.delete(0, tk.END)
def divide(self):
self.operator = "/"
self.first_number = float(self.display.get())
self.display.delete(0, tk.END)
def calculate(self):
second_number = float(self.display.get())
self.display.delete(0, tk.END)
if self.operator == "+":
result = self.first_number + second_number
elif self.operator == "-":
result = self.first_number - second_number
elif self.operator == "*":
result = self.first_number * second_number
elif self.operator == "/":
result = self.first_number / second_number
self.display.insert(0, str(result))
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()
```
运行以上代码,将会生成一个简单的计算器应用。
阅读全文