基于python,编写一个GUI界面的计算器,可以进行加减乘除等计算,如果计算出现异常显示guoyujia
时间: 2024-01-20 20:02:32 浏览: 63
好的,我可以帮你实现一个基于Python的GUI计算器,以下是代码:
```python
import tkinter as tk
class Calculator:
def __init__(self, master):
self.master = master
master.title("计算器")
# 创建显示结果的文本框
self.result = tk.StringVar()
self.result.set("0")
self.display = tk.Label(master, textvariable=self.result, width=25, height=2, font=('Arial', 16))
self.display.grid(row=0, column=0, columnspan=4)
# 创建数字按钮
button_list = [
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
]
r = 1
c = 0
for b in button_list:
command = lambda x=b: self.button_click(x)
tk.Button(master, text=b, width=5, height=2, font=('Arial', 16), command=command).grid(row=r, column=c)
c += 1
if c > 3:
c = 0
r += 1
def button_click(self, key):
if key == "=":
# 计算结果
try:
result = str(eval(self.result.get()))
except:
result = "guoyujia"
self.result.set(result)
elif key == "C":
# 清空文本框
self.result.set("0")
else:
# 在文本框中添加字符
if self.result.get() == "0":
self.result.set("")
self.result.set(self.result.get() + key)
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()
```
运行代码后,会弹出一个计算器的GUI界面,可以进行加减乘除等计算。如果计算出现异常,结果将会显示为“guoyujia”。
阅读全文