用tkinter编写一个计算器 功能包括普通计算器 程序员计算器 科学计算器
时间: 2023-08-14 17:02:51 浏览: 146
好的,我可以帮你完成这个任务。以下是一个基本的框架,你可以根据需要进行修改和完善:
```python
import tkinter as tk
from tkinter import ttk
class Calculator:
def __init__(self):
self.root = tk.Tk()
self.root.title("Calculator")
# 创建菜单栏
menubar = tk.Menu(self.root)
self.root.config(menu=menubar)
# 创建“文件”菜单
file_menu = tk.Menu(menubar)
file_menu.add_command(label="退出", command=self.root.quit)
menubar.add_cascade(label="文件", menu=file_menu)
# 创建标签和输入框
self.label = tk.Label(self.root, text="0", anchor="e", font=("Helvetica", 20))
self.label.grid(row=0, column=0, columnspan=4, sticky="nsew")
# 创建按钮
button_list = [
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
]
row_index = 1
col_index = 0
for button_text in button_list:
button = ttk.Button(self.root, text=button_text, command=lambda button_text=button_text:self.button_click(button_text))
button.grid(row=row_index, column=col_index, sticky="nsew")
col_index += 1
if col_index > 3:
col_index = 0
row_index += 1
self.root.mainloop()
def button_click(self, text):
pass
if __name__ == "__main__":
Calculator()
```
这是一个基本的计算器界面,包括一个标签和一个输入框,以及一系列数字和运算符按钮。现在你需要根据需要添加相应的功能,比如普通计算器、程序员计算器、科学计算器等。你可以根据需要添加新的按钮,或者修改已有的按钮的行为。例如,你可以在`button_click`方法中处理按钮点击事件,根据按钮文本执行相应的计算或操作。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)