简易计算器,窗口界面自由发挥,编程实现两个整数的加、减、乘、除操作。要求如下: - 首先进行操作数文本框检验,检验输入数据是否为纯数字; - 通过分别单击加、减、乘、除按钮,对操作数1与操作数2进行相应加、减、乘、除操作,并且将其结果写入操作3文本框。
时间: 2023-07-10 10:20:04 浏览: 44
好的,这是一个简单的计算器程序,我将使用Python编写,并使用Tkinter库创建窗口界面。以下是代码实现:
```python
from tkinter import *
def is_number(num):
try:
float(num)
return True
except ValueError:
return False
def add():
if is_number(num1.get()) and is_number(num2.get()):
result.set(float(num1.get()) + float(num2.get()))
else:
result.set("Error")
def subtract():
if is_number(num1.get()) and is_number(num2.get()):
result.set(float(num1.get()) - float(num2.get()))
else:
result.set("Error")
def multiply():
if is_number(num1.get()) and is_number(num2.get()):
result.set(float(num1.get()) * float(num2.get()))
else:
result.set("Error")
def divide():
if is_number(num1.get()) and is_number(num2.get()) and float(num2.get()) != 0:
result.set(float(num1.get()) / float(num2.get()))
else:
result.set("Error")
# 创建窗口
root = Tk()
root.title("Calculator")
# 创建操作数1、操作数2以及结果文本框
num1 = Entry(root)
num1.pack(side=LEFT)
num2 = Entry(root)
num2.pack(side=LEFT)
result = StringVar()
result.set("")
output = Label(root, textvariable=result)
output.pack(side=LEFT)
# 创建加、减、乘、除按钮
add_button = Button(root, text="+", command=add)
add_button.pack(side=LEFT)
subtract_button = Button(root, text="-", command=subtract)
subtract_button.pack(side=LEFT)
multiply_button = Button(root, text="*", command=multiply)
multiply_button.pack(side=LEFT)
divide_button = Button(root, text="/", command=divide)
divide_button.pack(side=LEFT)
# 运行窗口
root.mainloop()
```
在这个程序中,我们使用了四个函数 `add()`、`subtract()`、`multiply()` 和 `divide()`,分别对应加、减、乘、除操作。这些函数会检查操作数1和操作数2是否为纯数字,如果是,则进行相应的计算,并将结果写入结果文本框中,否则将结果文本框设为 "Error"。我们还使用了 `is_number()` 函数来检查一个字符串是否为纯数字。
通过使用 Tkinter 库,我们创建了一个简单的窗口界面,包括操作数1、操作数2和结果文本框以及四个按钮,单击按钮会调用相应的函数进行计算。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)