利用python GUI之tkinter编写界面计算器,基于面向对象编程,编写一个具备+、-、*、/四则运算的计算器,要求采用连续计算模式
时间: 2024-06-04 07:12:07 浏览: 108
(即支持多次连续计算)。
以下是代码实现:
```python
import tkinter as tk
class Calculator:
def __init__(self, master):
self.master = master
master.title("计算器")
# 创建显示框
self.display = tk.Entry(master, width=24, font=('Arial', 16))
self.display.grid(row=0, column=0, columnspan=4, pady=10)
# 创建按钮
self.create_button("7", 1, 0)
self.create_button("8", 1, 1)
self.create_button("9", 1, 2)
self.create_button("/", 1, 3)
self.create_button("4", 2, 0)
self.create_button("5", 2, 1)
self.create_button("6", 2, 2)
self.create_button("*", 2, 3)
self.create_button("1", 3, 0)
self.create_button("2", 3, 1)
self.create_button("3", 3, 2)
self.create_button("-", 3, 3)
self.create_button("0", 4, 0)
self.create_button(".", 4, 1)
self.create_button("C", 4, 2)
self.create_button("+", 4, 3)
self.create_button("=", 5, 0, columnspan=4)
# 初始化变量
self.result = 0
self.operator = "+"
self.is_new_number = True
def create_button(self, text, row, column, rowspan=1, columnspan=1):
button = tk.Button(self.master, text=text, width=6, height=2, font=('Arial', 16),
command=lambda:self.button_click(text))
button.grid(row=row, column=column, rowspan=rowspan, columnspan=columnspan, padx=5, pady=5)
def button_click(self, text):
if text.isdigit() or text == ".":
if self.is_new_number:
self.display.delete(0, tk.END)
self.is_new_number = False
self.display.insert(tk.END, text)
elif text == "C":
self.display.delete(0, tk.END)
self.result = 0
self.operator = "+"
elif text in ["+", "-", "*", "/"]:
self.calculate()
self.result = float(self.display.get())
self.operator = text
self.is_new_number = True
elif text == "=":
self.calculate()
self.operator = "+"
self.is_new_number = True
def calculate(self):
number = float(self.display.get())
if self.operator == "+":
self.result += number
elif self.operator == "-":
self.result -= number
elif self.operator == "*":
self.result *= number
elif self.operator == "/":
self.result /= number
self.display.delete(0, tk.END)
self.display.insert(tk.END, str(self.result))
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()
```
运行程序,即可得到一个简单的计算器界面。
![calculator](https://cdn.jsdelivr.net/gh/1077645536/CDN/blog/images/calculator.png)
阅读全文