帮我用python写一个带GUI的计算器的程序
时间: 2023-08-28 18:41:05 浏览: 104
好的,这里是一个简单的 Python GUI 计算器程序,使用 tkinter 模块构建:
```python
import tkinter as tk
class Calculator:
def __init__(self, master):
self.master = master
master.title("简单计算器")
# 创建输入框
self.entry = tk.Entry(master, width=20, font=('Arial', 16))
self.entry.grid(row=0, column=0, columnspan=4, padx=5, pady=5)
# 创建数字按钮
for i in range(10):
tk.Button(master, text=str(i), width=5, height=2, command=lambda num=i: self.button_click(str(num))).grid(row=(i//3)+1, column=i%3, padx=5, pady=5)
# 创建操作符按钮
tk.Button(master, text='+', width=5, height=2, command=lambda: self.button_click('+')).grid(row=1, column=3, padx=5, pady=5)
tk.Button(master, text='-', width=5, height=2, command=lambda: self.button_click('-')).grid(row=2, column=3, padx=5, pady=5)
tk.Button(master, text='*', width=5, height=2, command=lambda: self.button_click('*')).grid(row=3, column=3, padx=5, pady=5)
tk.Button(master, text='/', width=5, height=2, command=lambda: self.button_click('/')).grid(row=4, column=3, padx=5, pady=5)
# 创建功能按钮
tk.Button(master, text='AC', width=5, height=2, command=self.clear_entry).grid(row=1, column=0, padx=5, pady=5)
tk.Button(master, text='←', width=5, height=2, command=self.delete_entry).grid(row=1, column=1, padx=5, pady=5)
tk.Button(master, text='=', width=5, height=2, command=self.calculate).grid(row=4, column=2, padx=5, pady=5)
tk.Button(master, text='.', width=5, height=2, command=lambda: self.button_click('.')).grid(row=4, column=1, padx=5, pady=5)
# 按钮点击事件
def button_click(self, num):
self.entry.insert(tk.END, num)
# 清空输入框
def clear_entry(self):
self.entry.delete(0, tk.END)
# 删除输入框最后一个字符
def delete_entry(self):
self.entry.delete(len(self.entry.get())-1, tk.END)
# 计算结果
def calculate(self):
expression = self.entry.get()
try:
result = eval(expression)
self.entry.delete(0, tk.END)
self.entry.insert(0, result)
except:
self.clear_entry()
self.entry.insert(0, "Error")
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()
```
这个程序将创建一个简单的 GUI 界面,包括一个输入框和各种数字、操作符、功能按钮。你可以点击按钮输入数字和运算符,也可以点击功能按钮进行清空、删除和计算。程序会根据输入的表达式计算并输出结果,如果出现错误,会在输入框中显示 "Error"。
阅读全文