简易计算器,窗口界面自由发挥,编程实现两个整数的加、减、乘、除操作。要求如下: - 首先进行操作数文本框检验,检验输入数据是否为纯数字; - 通过分别单击加、减、乘、除按钮,对操作数1与操作数2进行相应加、减、乘、除操作,并且将其结果写入操作3文本框。
时间: 2023-07-10 16:11:57 浏览: 76
好的,这是一个简单的计算器程序,你可以使用Python编写,并且使用Tkinter库来创建窗口界面。下面是一个示例代码,你可以参考一下:
```python
import tkinter as tk
class Calculator:
def __init__(self, master):
self.master = master
master.title("简易计算器")
# 创建标签和文本框
self.label1 = tk.Label(master, text="操作数1: ")
self.label1.grid(row=0, column=0)
self.entry1 = tk.Entry(master)
self.entry1.grid(row=0, column=1)
self.label2 = tk.Label(master, text="操作数2: ")
self.label2.grid(row=1, column=0)
self.entry2 = tk.Entry(master)
self.entry2.grid(row=1, column=1)
self.label3 = tk.Label(master, text="结果: ")
self.label3.grid(row=2, column=0)
self.entry3 = tk.Entry(master, state="readonly")
self.entry3.grid(row=2, column=1)
# 创建按钮
self.button_add = tk.Button(master, text="+", command=self.add)
self.button_add.grid(row=3, column=0)
self.button_subtract = tk.Button(master, text="-", command=self.subtract)
self.button_subtract.grid(row=3, column=1)
self.button_multiply = tk.Button(master, text="×", command=self.multiply)
self.button_multiply.grid(row=4, column=0)
self.button_divide = tk.Button(master, text="÷", command=self.divide)
self.button_divide.grid(row=4, column=1)
def add(self):
if self.check_input():
result = int(self.entry1.get()) + int(self.entry2.get())
self.entry3.config(state="normal")
self.entry3.delete(0, "end")
self.entry3.insert(0, result)
self.entry3.config(state="readonly")
def subtract(self):
if self.check_input():
result = int(self.entry1.get()) - int(self.entry2.get())
self.entry3.config(state="normal")
self.entry3.delete(0, "end")
self.entry3.insert(0, result)
self.entry3.config(state="readonly")
def multiply(self):
if self.check_input():
result = int(self.entry1.get()) * int(self.entry2.get())
self.entry3.config(state="normal")
self.entry3.delete(0, "end")
self.entry3.insert(0, result)
self.entry3.config(state="readonly")
def divide(self):
if self.check_input():
if int(self.entry2.get()) == 0:
self.entry3.config(state="normal")
self.entry3.delete(0, "end")
self.entry3.insert(0, "Error")
self.entry3.config(state="readonly")
else:
result = int(self.entry1.get()) / int(self.entry2.get())
self.entry3.config(state="normal")
self.entry3.delete(0, "end")
self.entry3.insert(0, result)
self.entry3.config(state="readonly")
def check_input(self):
try:
int(self.entry1.get())
int(self.entry2.get())
return True
except ValueError:
self.entry3.config(state="normal")
self.entry3.delete(0, "end")
self.entry3.insert(0, "Error")
self.entry3.config(state="readonly")
return False
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()
```
这个程序创建了一个简单的GUI界面,包括两个标签和三个文本框,以及四个按钮。在用户点击按钮时,程序会根据用户输入的两个操作数,进行相应的加、减、乘、除操作,并将结果显示在第三个文本框中。同时,程序会检查用户输入的操作数是否为纯数字,如果不是,则在结果文本框中显示"Error"。
阅读全文