使用tkinter制作一个简单的计算器,能完成浮点数的加减乘除计算。(一个浮点数不能包含两个小数点)
时间: 2024-06-09 15:07:41 浏览: 40
python使用tkinter实现简单计算器
好的,下面是一个使用tkinter制作的简单计算器的代码:
```python
import tkinter as tk
class Calculator:
def __init__(self, master):
self.master = master
self.master.title("Calculator")
self.master.resizable(width=False, height=False)
self.display = tk.Entry(self.master, width=20, justify='right', font=('Arial', 16))
self.display.grid(row=0, column=0, columnspan=4, padx=5, pady=5)
self.buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+'
]
for row in range(4):
for col in range(4):
index = row * 4 + col
button = tk.Button(self.master, text=self.buttons[index], width=4, height=2, font=('Arial', 16))
button.grid(row=row+1, column=col, padx=5, pady=5)
button.bind('<Button-1>', self.button_click)
self.reset()
def reset(self):
self.operator = None
self.operand = 0.0
self.display.delete(0, tk.END)
def button_click(self, event):
text = event.widget['text']
if text.isdigit() or text == '.':
if '.' in self.display.get() and text == '.':
return
self.display.insert(tk.END, text)
elif text in '+-*/':
self.operand = float(self.display.get())
self.operator = text
self.display.delete(0, tk.END)
elif text == '=':
if self.operator is None:
return
result = 0.0
if self.operator == '+':
result = self.operand + float(self.display.get())
elif self.operator == '-':
result = self.operand - float(self.display.get())
elif self.operator == '*':
result = self.operand * float(self.display.get())
elif self.operator == '/':
result = self.operand / float(self.display.get())
self.display.delete(0, tk.END)
self.display.insert(tk.END, str(result))
self.operator = None
elif text == 'C':
self.reset()
if __name__ == '__main__':
root = tk.Tk()
app = Calculator(root)
root.mainloop()
```
运行上述代码,即可弹出一个简单的计算器界面,可以进行浮点数的加减乘除计算。
阅读全文