欢迎访问宙启技术站
智能推送

用Python编写的简单图形界面计算器

发布时间:2023-12-04 19:54:57

以下是一个简单的Python图形界面计算器示例代码,使用了tkinter库。这个计算器可以进行基本的数学运算,包括加法、减法、乘法和除法。

import tkinter as tk

def calculate():
    try:
        num1 = float(entry1.get())
        num2 = float(entry2.get())
        operation = combo.get()
        
        if operation == "+":
            result = num1 + num2
        elif operation == "-":
            result = num1 - num2
        elif operation == "*":
            result = num1 * num2
        elif operation == "/":
            result = num1 / num2
            
        label_result.config(text="结果:" + str(result))
    except ValueError:
        label_result.config(text="请输入有效的数字!")
    except ZeroDivisionError:
        label_result.config(text="除数不能为0!")

root = tk.Tk()
root.title("简单计算器")

label1 = tk.Label(root, text="第一个数:")
label1.grid(row=0, column=0)

entry1 = tk.Entry(root)
entry1.grid(row=0, column=1)

label2 = tk.Label(root, text="第二个数:")
label2.grid(row=1, column=0)

entry2 = tk.Entry(root)
entry2.grid(row=1, column=1)

label3 = tk.Label(root, text="运算符:")
label3.grid(row=2, column=0)

options = ["+", "-", "*", "/"]
combo = tk.ttk.Combobox(root, values=options)
combo.grid(row=2, column=1)
combo.current(0)

button = tk.Button(root, text="计算", command=calculate)
button.grid(row=3, column=0, columnspan=2)

label_result = tk.Label(root)
label_result.grid(row=4, column=0, columnspan=2)

root.mainloop()

使用该计算器很简单。首先,用户需要在第一个输入框中输入第一个数,然后在第二个输入框中输入第二个数。接下来,用户选择一个运算符(加号、减号、乘号或除号)。最后,用户点击"计算"按钮,计算结果将显示在结果标签中。

这个计算器具有一定的错误处理机制。如果用户输入的数不是有效的数字,或者尝试进行除以零的操作,程序会显示适当的错误消息。

希望这个示例能够帮助你理解并实现一个简单的Python图形界面计算器。