1. 简易计算器,窗口界面自由发挥,编程实现两个整数的**加**、**减**、**乘**、**除**操作。要求如下: - 首先进行操作数文本框检验,检验输入数据是否为**纯数字**; - 通过分别单击加、减、乘、除按钮,对操作数1与操作数2进行相应加、减、乘、除操作,并且将其结果写入操作3文本框。python
时间: 2023-07-23 14:18:56 浏览: 90
好的,我可以为你提供一个简单的计算器的代码,如下所示:
```python
import tkinter as tk
def add():
try:
operand1 = float(entry1.get())
operand2 = float(entry2.get())
result = operand1 + operand2
entry3.delete(0, tk.END)
entry3.insert(0, result)
except ValueError:
entry3.delete(0, tk.END)
entry3.insert(0, "Invalid Input")
def subtract():
try:
operand1 = float(entry1.get())
operand2 = float(entry2.get())
result = operand1 - operand2
entry3.delete(0, tk.END)
entry3.insert(0, result)
except ValueError:
entry3.delete(0, tk.END)
entry3.insert(0, "Invalid Input")
def multiply():
try:
operand1 = float(entry1.get())
operand2 = float(entry2.get())
result = operand1 * operand2
entry3.delete(0, tk.END)
entry3.insert(0, result)
except ValueError:
entry3.delete(0, tk.END)
entry3.insert(0, "Invalid Input")
def divide():
try:
operand1 = float(entry1.get())
operand2 = float(entry2.get())
result = operand1 / operand2
entry3.delete(0, tk.END)
entry3.insert(0, result)
except ValueError:
entry3.delete(0, tk.END)
entry3.insert(0, "Invalid Input")
except ZeroDivisionError:
entry3.delete(0, tk.END)
entry3.insert(0, "Cannot divide by zero")
root = tk.Tk()
root.title("Calculator")
label1 = tk.Label(root, text="Operand 1: ")
label1.grid(row=0, column=0)
entry1 = tk.Entry(root)
entry1.grid(row=0, column=1)
label2 = tk.Label(root, text="Operand 2: ")
label2.grid(row=1, column=0)
entry2 = tk.Entry(root)
entry2.grid(row=1, column=1)
label3 = tk.Label(root, text="Result: ")
label3.grid(row=2, column=0)
entry3 = tk.Entry(root)
entry3.grid(row=2, column=1)
button_add = tk.Button(root, text="+", command=add)
button_add.grid(row=3, column=0)
button_subtract = tk.Button(root, text="-", command=subtract)
button_subtract.grid(row=3, column=1)
button_multiply = tk.Button(root, text="*", command=multiply)
button_multiply.grid(row=4, column=0)
button_divide = tk.Button(root, text="/", command=divide)
button_divide.grid(row=4, column=1)
root.mainloop()
```
在这个代码中,我们使用了 `tkinter` 库来创建窗口和控件。我们创建了三个文本框,分别用于输入操作数1、操作数2和结果,以及四个按钮,分别对应加、减、乘、除操作。当用户单击任何一个按钮时,程序将尝试从文本框中获取操作数1和操作数2,并执行相应的计算操作。如果输入的数据不是纯数字,则程序将在结果文本框中显示 "Invalid Input"。如果用户试图除以零,则程序将在结果文本框中显示 "Cannot divide by zero"。
阅读全文