实现 GUI 版的简易计算器
时间: 2023-06-18 20:05:43 浏览: 98
计算器 GUI 实现简单
好的,以下是一个简易的计算器的 GUI 实现,使用 Python 的 tkinter 模块:
```python
from tkinter import *
class Calculator:
def __init__(self, master):
self.master = master
master.title("简易计算器")
self.display = Entry(master, width=30, justify=RIGHT, font=('Arial', 16))
self.display.grid(row=0, column=0, columnspan=4, padx=10, pady=10)
# 按钮
self.create_button("7", 1, 0)
self.create_button("8", 1, 1)
self.create_button("9", 1, 2)
self.create_button("+", 1, 3)
self.create_button("4", 2, 0)
self.create_button("5", 2, 1)
self.create_button("6", 2, 2)
self.create_button("-", 2, 3)
self.create_button("1", 3, 0)
self.create_button("2", 3, 1)
self.create_button("3", 3, 2)
self.create_button("*", 3, 3)
self.create_button("0", 4, 0)
self.create_button(".", 4, 1)
self.create_button("C", 4, 2)
self.create_button("/", 4, 3)
self.create_button("=", 5, 0, columnspan=4)
def create_button(self, text, row, column, columnspan=1):
button = Button(self.master, text=text, width=6, height=2, font=('Arial', 16),
command=lambda:self.button_click(text))
button.grid(row=row, column=column, columnspan=columnspan, padx=5, pady=5)
def button_click(self, text):
if text == "C":
self.display.delete(0, END)
elif text == "=":
try:
result = eval(self.display.get())
self.display.delete(0, END)
self.display.insert(0, str(result))
except:
self.display.delete(0, END)
self.display.insert(0, "Error")
else:
self.display.insert(END, text)
root = Tk()
calculator = Calculator(root)
root.mainloop()
```
运行后会弹出一个计算器窗口,可以进行简单的加减乘除运算,也支持清空和计算结果。
阅读全文