python实现一个有窗口的计算器
时间: 2024-02-18 12:59:46 浏览: 27
好的,以下是一个简单的 Python 计算器 GUI 实现:
```python
import tkinter as tk
# 定义函数实现加法
def add():
num1 = float(num1_entry.get())
num2 = float(num2_entry.get())
result = num1 + num2
result_label.config(text="计算结果:%.2f" % result)
# 定义函数实现减法
def subtract():
num1 = float(num1_entry.get())
num2 = float(num2_entry.get())
result = num1 - num2
result_label.config(text="计算结果:%.2f" % result)
# 定义函数实现乘法
def multiply():
num1 = float(num1_entry.get())
num2 = float(num2_entry.get())
result = num1 * num2
result_label.config(text="计算结果:%.2f" % result)
# 定义函数实现除法
def divide():
num1 = float(num1_entry.get())
num2 = float(num2_entry.get())
result = num1 / num2
result_label.config(text="计算结果:%.2f" % result)
# 创建主窗口
root = tk.Tk()
root.title("计算器")
# 创建标签和输入框
num1_label = tk.Label(root, text="第一个数字:")
num1_label.grid(row=0, column=0)
num1_entry = tk.Entry(root)
num1_entry.grid(row=0, column=1)
num2_label = tk.Label(root, text="第二个数字:")
num2_label.grid(row=1, column=0)
num2_entry = tk.Entry(root)
num2_entry.grid(row=1, column=1)
result_label = tk.Label(root, text="计算结果:")
result_label.grid(row=2, column=0, columnspan=2)
# 创建按钮
add_button = tk.Button(root, text="+", command=add)
add_button.grid(row=3, column=0)
subtract_button = tk.Button(root, text="-", command=subtract)
subtract_button.grid(row=3, column=1)
multiply_button = tk.Button(root, text="*", command=multiply)
multiply_button.grid(row=4, column=0)
divide_button = tk.Button(root, text="/", command=divide)
divide_button.grid(row=4, column=1)
# 运行主循环
root.mainloop()
```
使用该计算器,您可以在窗口中输入两个数字和运算符,然后得到计算结果。该实现使用 Tkinter 库创建了一个简单的 GUI 界面,并将输入框、标签和按钮添加到窗口中。当用户按下按钮时,相应的函数将被调用以执行计算,并在标签中显示结果。请注意,此实现仅支持基本的加减乘除运算符。