基于python,编写一个GUI界面的计算器并带有全清键、清除键、清除输入键、平方根,可以进行加减乘除等计算,如果计算出现异常显示guoyujia
时间: 2024-02-03 11:01:41 浏览: 63
好的,我可以帮你实现一个带有全清键、清除键、清除输入键、平方根的基于Python的GUI计算器,以下是代码:
```python
import tkinter as tk
import math
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=5)
# 创建数字按钮
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
# 创建清除键
clear_button = tk.Button(master, text="C", width=5, height=2, font=('Arial', 16), command=lambda: self.result.set("0"))
clear_button.grid(row=5, column=0)
# 创建全清键
all_clear_button = tk.Button(master, text="AC", width=5, height=2, font=('Arial', 16), command=self.all_clear)
all_clear_button.grid(row=5, column=1)
# 创建清除输入键
backspace_button = tk.Button(master, text="←", width=5, height=2, font=('Arial', 16), command=self.backspace)
backspace_button.grid(row=5, column=2)
# 创建平方根键
sqrt_button = tk.Button(master, text="√", width=5, height=2, font=('Arial', 16), command=self.sqrt)
sqrt_button.grid(row=5, column=3)
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)
def all_clear(self):
# 清空文本框
self.result.set("0")
def backspace(self):
# 删除最后一个字符
self.result.set(self.result.get()[:-1])
def sqrt(self):
# 计算平方根
try:
result = str(math.sqrt(float(self.result.get())))
except:
result = "guoyujia"
self.result.set(result)
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()
```
运行代码后,会弹出一个计算器的GUI界面,可以进行加减乘除等计算。如果计算出现异常,结果将会显示为“guoyujia”。同时,界面上还有全清键、清除键、清除输入键、平方根键,可以进行相应的操作。
阅读全文