使用tkinter制作一个简单的计算器,能完成浮点数的加减乘除计算。(一个浮点数不能包含两个小数点)
时间: 2024-04-30 14:19:14 浏览: 120
好的,以下是一个简单的计算器实现:
```python
import tkinter as tk
# 创建窗口
window = tk.Tk()
window.title('计算器')
# 创建显示框
display = tk.Entry(window, width=30, justify='right')
display.grid(row=0, column=0, columnspan=4)
# 记录当前计算结果和操作符
result = 0
operator = ''
# 处理数字按钮点击事件
def on_number_click(number):
global operator
current = display.get()
if current == '0':
display.delete(0, tk.END)
if '.' in current and number == '.':
return
display.insert(tk.END, number)
# 处理操作符按钮点击事件
def on_operator_click(op):
global result, operator
if operator == '':
result = float(display.get())
else:
result = eval(str(result) + operator + display.get())
operator = op
display.delete(0, tk.END)
# 处理等号按钮点击事件
def on_equal_click():
global result, operator
result = eval(str(result) + operator + display.get())
operator = ''
display.delete(0, tk.END)
display.insert(tk.END, result)
# 处理清除按钮点击事件
def on_clear_click():
global result, operator
result = 0
operator = ''
display.delete(0, tk.END)
display.insert(tk.END, '0')
# 创建数字按钮
for i in range(10):
tk.Button(window, text=str(i), command=lambda number=i: on_number_click(str(number))).grid(row=3 - i // 3, column=i % 3)
# 创建操作符按钮
tk.Button(window, text='+', command=lambda: on_operator_click('+')).grid(row=1, column=3)
tk.Button(window, text='-', command=lambda: on_operator_click('-')).grid(row=2, column=3)
tk.Button(window, text='*', command=lambda: on_operator_click('*')).grid(row=3, column=3)
tk.Button(window, text='/', command=lambda: on_operator_click('/')).grid(row=4, column=3)
tk.Button(window, text='.', command=lambda: on_number_click('.')).grid(row=4, column=2)
tk.Button(window, text='=', command=on_equal_click).grid(row=4, column=1)
tk.Button(window, text='C', command=on_clear_click).grid(row=4, column=0)
# 运行窗口
window.mainloop()
```
这个计算器使用了 Tkinter 库来创建 GUI 界面,实现了加减乘除四则运算以及小数点输入和清除功能。你可以根据需要进行修改和扩展。
阅读全文