在GUI下实现一个加减乘除运算器,接受任意两个数字的输入,计算两者的和、差、积、商
时间: 2023-06-20 15:10:34 浏览: 88
好的,我可以给您提供一个Python代码示例,使用Tkinter模块实现一个简单的GUI加减乘除运算器。以下是示例代码:
```python
import tkinter as tk
class Calculator:
def __init__(self, master):
self.master = master
master.title("Calculator")
# 创建输入框和标签
self.num1_label = tk.Label(master, text="Number 1:")
self.num1_label.grid(row=0, column=0)
self.num1_entry = tk.Entry(master)
self.num1_entry.grid(row=0, column=1)
self.num2_label = tk.Label(master, text="Number 2:")
self.num2_label.grid(row=1, column=0)
self.num2_entry = tk.Entry(master)
self.num2_entry.grid(row=1, column=1)
self.result_label = tk.Label(master, text="")
self.result_label.grid(row=4, column=0, columnspan=2)
# 创建四个按钮
self.add_button = tk.Button(master, text="+", command=self.add)
self.add_button.grid(row=2, column=0)
self.subtract_button = tk.Button(master, text="-", command=self.subtract)
self.subtract_button.grid(row=2, column=1)
self.multiply_button = tk.Button(master, text="*", command=self.multiply)
self.multiply_button.grid(row=3, column=0)
self.divide_button = tk.Button(master, text="/", command=self.divide)
self.divide_button.grid(row=3, column=1)
def add(self):
try:
num1 = float(self.num1_entry.get())
num2 = float(self.num2_entry.get())
result = num1 + num2
self.result_label.config(text="Result: " + str(result))
except ValueError:
self.result_label.config(text="Please enter valid numbers")
def subtract(self):
try:
num1 = float(self.num1_entry.get())
num2 = float(self.num2_entry.get())
result = num1 - num2
self.result_label.config(text="Result: " + str(result))
except ValueError:
self.result_label.config(text="Please enter valid numbers")
def multiply(self):
try:
num1 = float(self.num1_entry.get())
num2 = float(self.num2_entry.get())
result = num1 * num2
self.result_label.config(text="Result: " + str(result))
except ValueError:
self.result_label.config(text="Please enter valid numbers")
def divide(self):
try:
num1 = float(self.num1_entry.get())
num2 = float(self.num2_entry.get())
if num2 == 0:
self.result_label.config(text="Cannot divide by zero")
else:
result = num1 / num2
self.result_label.config(text="Result: " + str(result))
except ValueError:
self.result_label.config(text="Please enter valid numbers")
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()
```
这个程序会创建一个窗口,包括两个输入框和四个按钮,用于进行加减乘除运算。当用户点击按钮时,程序会尝试将输入转换为浮点数,并计算结果。如果输入无法转换为数字,则程序会显示一个错误消息。如果除数为零,则程序会显示一个除以零的错误消息。计算结果将显示在标签中。
阅读全文