python 图形界面设计计算器实现 回退 和清空 。以及带有退出功能的菜单
时间: 2024-02-16 20:01:08 浏览: 378
python界面计算器
好的,针对你的问题,我可以给出一份简单的Python代码实现,如下:
```python
import tkinter as tk
class Calculator:
def __init__(self, master):
self.master = master
master.title("Calculator")
self.equation = tk.StringVar()
self.equation.set("")
# 创建显示计算结果的文本框
self.result_display = tk.Entry(master, textvariable=self.equation, width=30, justify="right")
self.result_display.grid(row=0, column=0, columnspan=4, padx=5, pady=5)
# 创建清空和回退按钮
self.clear_button = tk.Button(master, text="C", width=5, command=self.clear)
self.clear_button.grid(row=1, column=0, padx=5, pady=5)
self.back_button = tk.Button(master, text="<-", width=5, command=self.backspace)
self.back_button.grid(row=1, column=1, padx=5, pady=5)
# 创建数字和运算符按钮
self.buttons = [
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "+", "="
]
self.create_buttons()
# 创建菜单
menu = tk.Menu(master)
master.config(menu=menu)
file_menu = tk.Menu(menu)
menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Exit", command=master.quit)
def create_buttons(self):
row = 2
col = 0
for button in self.buttons:
command = lambda x=button: self.handle_click(x)
if button == "0":
tk.Button(self.master, text=button, width=11, command=command).grid(row=row, column=col, columnspan=2, padx=5, pady=5)
col += 2
elif button == "=":
tk.Button(self.master, text=button, width=11, command=command).grid(row=row, column=col, columnspan=2, padx=5, pady=5)
row += 1
col = 0
else:
tk.Button(self.master, text=button, width=5, command=command).grid(row=row, column=col, padx=5, pady=5)
col += 1
def handle_click(self, button):
if button == "C":
self.clear()
elif button == "<-":
self.backspace()
elif button == "=":
try:
result = str(eval(self.equation.get()))
self.equation.set(result)
except:
self.equation.set("Error")
else:
self.equation.set(self.equation.get() + button)
def clear(self):
self.equation.set("")
def backspace(self):
current_equation = self.equation.get()
self.equation.set(current_equation[:-1])
root = tk.Tk()
calculator = Calculator(root)
root.mainloop()
```
代码中,我们使用了Tkinter库来创建了一个简单的图形界面计算器,实现了清空和回退功能,并加入了一个带有退出功能的菜单。你可以通过绑定按钮的command属性来实现按钮的功能。同时使用Menu和add_cascade方法创建菜单,并使用add_command方法来添加退出菜单项。
阅读全文