Python实现的简单计算器GUI界面示例
发布时间:2023-12-04 10:26:31
下面是一个使用Python编写的简单计算器GUI界面的示例代码:
import tkinter as tk
# 创建窗口
window = tk.Tk()
window.title("简单计算器")
# 创建显示结果的文本框
result_text = tk.StringVar()
result_label = tk.Label(window, textvariable=result_text, width=30, height=2, bg='white', font=('Arial', 16))
result_label.pack()
# 创建数字按钮的回调函数
def digit_button_clicked(digit):
current_value = result_text.get()
result_text.set(current_value + digit)
# 创建操作符按钮的回调函数
def operator_button_clicked(operator):
current_value = result_text.get()
# 检查当前值是否为一个合法的数字
try:
float(current_value)
except ValueError:
return
# 根据操作符进行相应的计算
if operator == '=':
try:
result = eval(current_value)
result_text.set(str(result))
except (SyntaxError, ZeroDivisionError):
result_text.set("错误")
elif operator == 'C':
result_text.set("")
else:
result_text.set(current_value + operator)
# 创建数字按钮
for i in range(1, 10):
button = tk.Button(window, text=str(i), width=5, height=2,
command=lambda digit=str(i): digit_button_clicked(digit))
button.grid(row=(i-1)//3+1, column=(i-1)%3)
button0 = tk.Button(window, text='0', width=5, height=2,
command=lambda digit='0': digit_button_clicked(digit))
button0.grid(row=4, column=0)
button_dot = tk.Button(window, text='.', width=5, height=2,
command=lambda digit='.': digit_button_clicked(digit))
button_dot.grid(row=4, column=1)
# 创建操作符按钮
operators = ['+', '-', '*', '/']
for i in range(4):
button = tk.Button(window, text=operators[i], width=5, height=2,
command=lambda opr=operators[i]: operator_button_clicked(opr))
button.grid(row=i+1, column=3)
button_equal = tk.Button(window, text='=', width=5, height=2,
command=lambda opr='=': operator_button_clicked(opr))
button_equal.grid(row=4, column=2)
button_clear = tk.Button(window, text='C', width=5, height=2,
command=lambda opr='C': operator_button_clicked(opr))
button_clear.grid(row=0, column=3)
# 运行窗口主循环
window.mainloop()
此示例中,我们使用了Python的tkinter库来创建一个简单的计算器GUI界面。计算器界面包括一个用于显示结果的文本框和一些数字按钮和操作符按钮。
计算器的基本原理是,通过点击数字按钮来将数字添加到显示结果的文本框中,然后再通过点击操作符按钮来执行相应的计算。
在代码中,我们定义了两个回调函数:digit_button_clicked和operator_button_clicked。digit_button_clicked函数用于处理数字按钮的点击动作,它将点击的数字添加到当前显示结果的文本框中。operator_button_clicked函数用于处理操作符按钮的点击动作,它根据点击的操作符进行相应的计算。
在创建按钮时,我们使用了lambda函数来为每个按钮绑定相应的回调函数,并传递相应的参数。
最后,我们使用window.mainloop()来运行窗口的主循环,以便窗口可以响应用户的交互操作。
使用示例:
1. 点击数字按钮1,结果文本框显示1。
2. 点击操作符按钮+,结果文本框显示1+。
3. 点击数字按钮2,结果文本框显示1+2。
4. 点击操作符按钮=,计算结果为3,结果文本框显示3。
5. 点击操作符按钮*,结果文本框显示3*。
6. 点击数字按钮4,结果文本框显示3*4。
7. 点击操作符按钮=,计算结果为12,结果文本框显示12。
8. 点击操作符按钮C,结果文本框清空,显示为空。
