1. 简易计算器,窗口界面自由发挥,编程实现两个整数的**加**、**减**、**乘**、**除**操作。要求如下: - 首先进行操作数文本框检验,检验输入数据是否为**纯数字**; - 通过分别单击加、减、乘、除按钮,对操作数1与操作数2进行相应加、减、乘、除操作,并且将其结果写入操作3文本框。
时间: 2023-07-23 12:11:07 浏览: 23
好的,这是一个很好的练手项目,我可以帮你实现这个简易计算器。你可以使用 Python 的 Tkinter 模块来创建窗口界面,下面是实现这个计算器的代码,请注意检查输入数据是否为纯数字:
```python
import tkinter as tk
def check_input(num):
try:
float(num)
return True
except ValueError:
return False
def add():
if check_input(num1.get()) and check_input(num2.get()):
result.set(float(num1.get()) + float(num2.get()))
def sub():
if check_input(num1.get()) and check_input(num2.get()):
result.set(float(num1.get()) - float(num2.get()))
def mul():
if check_input(num1.get()) and check_input(num2.get()):
result.set(float(num1.get()) * float(num2.get()))
def div():
if check_input(num1.get()) and check_input(num2.get()) and float(num2.get()) != 0:
result.set(float(num1.get()) / float(num2.get()))
else:
result.set("Error")
root = tk.Tk()
root.title("简易计算器")
tk.Label(root, text="操作数1:").grid(row=0, column=0)
num1 = tk.Entry(root)
num1.grid(row=0, column=1)
tk.Label(root, text="操作数2:").grid(row=1, column=0)
num2 = tk.Entry(root)
num2.grid(row=1, column=1)
tk.Button(root, text="加", command=add).grid(row=2, column=0)
tk.Button(root, text="减", command=sub).grid(row=2, column=1)
tk.Button(root, text="乘", command=mul).grid(row=3, column=0)
tk.Button(root, text="除", command=div).grid(row=3, column=1)
tk.Label(root, text="结果:").grid(row=4, column=0)
result = tk.StringVar()
result.set("")
tk.Entry(root, textvariable=result, state="readonly").grid(row=4, column=1)
root.mainloop()
```
在这个代码中,我们定义了四个函数 `add()`、`sub()`、`mul()`、`div()` 分别对应加、减、乘、除操作。这些函数检查输入数据是否为纯数字,并且将计算结果写入结果文本框。我们还创建了窗口界面,包括两个操作数文本框、四个操作按钮和一个结果文本框。
相关推荐
![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_column_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)