python 简易计算器,窗口界面自由发挥,编程实现两个整数的**加**、**减**、**乘**、**除**操作。要求如下: - 首先进行操作数文本框检验,检验输入数据是否为**纯数字**; - 通过分别单击加、减、乘、除按钮,对操作数1与操作数2进行相应加、减、乘、除操作,并且将其结果写入操作3文本框。
时间: 2023-07-23 07:11:34 浏览: 85
好的,这是一个简单的 Python GUI 计算器代码,可以实现加、减、乘、除等基本运算:
```python
import tkinter as tk
def calculate():
try:
num1 = int(entry1.get())
num2 = int(entry2.get())
except ValueError:
result.set("输入错误")
return
if operator.get() == "+":
result.set(num1 + num2)
elif operator.get() == "-":
result.set(num1 - num2)
elif operator.get() == "*":
result.set(num1 * num2)
elif operator.get() == "/":
if num2 == 0:
result.set("除数不能为0")
return
result.set(num1 / num2)
window = tk.Tk()
window.title("计算器")
label1 = tk.Label(window, text="操作数1:")
label1.grid(row=0, column=0)
entry1 = tk.Entry(window)
entry1.grid(row=0, column=1)
label2 = tk.Label(window, text="操作数2:")
label2.grid(row=1, column=0)
entry2 = tk.Entry(window)
entry2.grid(row=1, column=1)
operator = tk.StringVar()
operator.set("+")
add_button = tk.Radiobutton(window, text="+", variable=operator, value="+")
add_button.grid(row=2, column=0)
sub_button = tk.Radiobutton(window, text="-", variable=operator, value="-")
sub_button.grid(row=2, column=1)
mul_button = tk.Radiobutton(window, text="*", variable=operator, value="*")
mul_button.grid(row=2, column=2)
div_button = tk.Radiobutton(window, text="/", variable=operator, value="/")
div_button.grid(row=2, column=3)
calculate_button = tk.Button(window, text="计算", command=calculate)
calculate_button.grid(row=3, column=2)
label3 = tk.Label(window, text="结果:")
label3.grid(row=4, column=0)
result = tk.StringVar()
result.set("0")
entry3 = tk.Entry(window, textvariable=result)
entry3.grid(row=4, column=1)
window.mainloop()
```
这个代码使用了 tkinter 库来创建 GUI 窗口,其中包含了 2 个操作数文本框、4 个单选按钮、1 个计算按钮和 1 个结果文本框。在计算时,首先检验输入的数据是否为纯数字,如果不是则在结果文本框中显示“输入错误”,否则根据选中的单选按钮进行相应的计算,并将结果写入结果文本框。
阅读全文