编写程序实现一个简单的运算器,要求至少实现加减乘除四则运算,运算器功能界面排布尽量接近实际的运算器,数字输入通过界面上的数字按钮进行
时间: 2023-11-28 21:04:11 浏览: 92
以下是一个简单的 Python 运算器示例代码,实现了加减乘除四则运算:
```python
from tkinter import *
class Calculator:
def __init__(self, master):
self.master = master
master.title("Calculator")
# 创建一个文本框用于显示计算结果
self.result_display = Entry(master, width=20, font=('Arial', 16), justify=RIGHT)
self.result_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('4', 2, 0)
self.create_button('5', 2, 1)
self.create_button('6', 2, 2)
self.create_button('1', 3, 0)
self.create_button('2', 3, 1)
self.create_button('3', 3, 2)
self.create_button('0', 4, 1)
# 创建运算符按钮
self.create_button('+', 1, 3)
self.create_button('-', 2, 3)
self.create_button('*', 3, 3)
self.create_button('/', 4, 3)
# 创建其他按钮
self.create_button('C', 4, 0)
self.create_button('.', 4, 2)
self.create_button('=', 5, 3)
# 初始化变量
self.num1 = ''
self.num2 = ''
self.operator = ''
self.result = ''
def create_button(self, text, row, column):
button = Button(self.master, text=text, width=5, height=2, font=('Arial', 16), command=lambda:self.button_click(text))
button.grid(row=row, column=column, padx=2, pady=2)
def button_click(self, text):
if text.isdigit():
if not self.operator:
self.num1 += text
self.result_display.delete(0, END)
self.result_display.insert(0, self.num1)
else:
self.num2 += text
self.result_display.delete(0, END)
self.result_display.insert(0, self.num2)
elif text == '.':
if self.operator and '.' not in self.num2:
self.num2 += '.'
self.result_display.insert(END, '.')
elif not self.operator and '.' not in self.num1:
self.num1 += '.'
self.result_display.insert(END, '.')
elif text == 'C':
self.num1 = ''
self.num2 = ''
self.operator = ''
self.result = ''
self.result_display.delete(0, END)
elif text in ['+', '-', '*', '/']:
if self.num1 and self.num2:
self.calculate()
self.operator = text
elif text == '=':
if self.num1 and self.num2:
self.calculate()
def calculate(self):
num1 = float(self.num1)
num2 = float(self.num2)
if self.operator == '+':
self.result = num1 + num2
elif self.operator == '-':
self.result = num1 - num2
elif self.operator == '*':
self.result = num1 * num2
elif self.operator == '/':
self.result = num1 / num2
self.num1 = str(self.result)
self.num2 = ''
self.operator = ''
self.result_display.delete(0, END)
self.result_display.insert(0, self.result)
root = Tk()
calculator = Calculator(root)
root.mainloop()
```
使用 Tkinter 模块创建 GUI 界面,实现了数字按钮、运算符按钮、清除按钮和等于按钮的功能,同时实现了数字输入、小数点输入、运算符选择和计算等功能。
阅读全文