使用tkinter实现简易计算器:
时间: 2023-11-05 14:49:17 浏览: 110
好的,以下是一个使用 tkinter 实现的简易计算器:
```python
import tkinter as tk
class Calculator:
def __init__(self, master):
self.master = master
master.title("简易计算器")
# 定义显示结果的文本框
self.result_var = tk.StringVar()
self.result_var.set('')
self.result_entry = tk.Entry(master, textvariable=self.result_var, justify='right', font=('Arial', 16))
self.result_entry.grid(row=0, column=0, columnspan=4, sticky='nsew')
# 定义所有数字按钮
numbers = [
['7', '8', '9'],
['4', '5', '6'],
['1', '2', '3'],
['0', '.', '=']
]
for i, row in enumerate(numbers, start=1):
for j, num in enumerate(row):
button = tk.Button(master, text=num, font=('Arial', 16), command=lambda x=num: self.button_click(x))
button.grid(row=i, column=j, sticky='nsew')
# 定义所有运算符按钮
operators = ['/', '*', '-', '+']
for i, operator in enumerate(operators, start=1):
button = tk.Button(master, text=operator, font=('Arial', 16), command=lambda x=operator: self.button_click(x))
button.grid(row=i, column=3, sticky='nsew')
# 定义清除和退格按钮
clear_button = tk.Button(master, text='C', font=('Arial', 16), command=self.clear)
clear_button.grid(row=0, column=3, sticky='nsew')
back_button = tk.Button(master, text='<-', font=('Arial', 16), command=self.backspace)
back_button.grid(row=0, column=2, sticky='nsew')
def button_click(self, button):
if button == '=':
try:
result = eval(self.result_var.get())
self.result_var.set(str(result))
except:
self.result_var.set('Error')
else:
self.result_var.set(self.result_var.get() + button)
def clear(self):
self.result_var.set('')
def backspace(self):
self.result_var.set(self.result_var.get()[:-1])
root = tk.Tk()
app = Calculator(root)
root.mainloop()
```
这个计算器界面看起来像这样:
![calculator](https://i.loli.net/2021/04/28/g1YiUMkJaH3wZSf.png)
你可以复制以上代码并运行它。
阅读全文