Python quickly implements a simple calculator with a clickable interface

        This article will take you to explore how to use Python to create an intuitive and practical calculator with an interface. We will introduce in depth how to use Python's graphical user interface library, especially Tkinter, to build a user-friendly interface that allows you to easily perform mathematical operations. Whether you are a beginner or have some programming experience, this article will provide you with clear steps and sample code to help you quickly build your own calculator application. No need to worry about complicated math calculations, this article will explain how to implement basic operations such as addition, subtraction, multiplication and division, as well as how to handle incorrect input.

Go directly to the source code:

import tkinter as tk

# 创建主窗口
root = tk.Tk()
root.title("简单计算器")

# 添加显示结果的文本框
result_var = tk.StringVar()
result_var.set("0")

result_display = tk.Entry(root, textvariable=result_var, font=("Arial", 20), bd=10, insertwidth=4, width=14, justify="right")
result_display.grid(row=0, column=0, columnspan=4)

# 定义计算器操作函数
def button_click(value):
    current_result = result_var.get()
    if current_result == "0":
        result_var.set(value)
    else:
        result_var.set(current_result + value)

def clear():
    result_var.set("0")

def calculate():
    try:
        expression = result_var.get()
        result = eval(expression)
        result_var.set(result)
    except Exception as e:
        result_var.set("错误")

# 创建按钮
button_texts = [
    ("7", 1, 0), ("8", 1, 1), ("9", 1, 2), ("/", 1, 3),
    ("4", 2, 0), ("5", 2, 1), ("6", 2, 2), ("*", 2, 3),
    ("1", 3, 0), ("2", 3, 1), ("3", 3, 2), ("-", 3, 3),
    ("0", 4, 0), (".", 4, 1), ("=", 4, 2), ("+", 4, 3)
]

for (text, row, col) in button_texts:
    button = tk.Button(root, text=text, font=("Arial", 20), padx=20, pady=20, command=lambda t=text: button_click(t))
    button.grid(row=row, column=col)

# 清除按钮
clear_button = tk.Button(root, text="C", font=("Arial", 20), padx=20, pady=20, command=clear)
clear_button.grid(row=5, column=0)

# 运行按钮
equal_button = tk.Button(root, text="=", font=("Arial", 20), padx=20, pady=20, command=calculate)
equal_button.grid(row=5, column=2)

# 主事件循环
root.mainloop()

The running results are as follows (with basic addition, subtraction, multiplication and division functions):

Guess you like

Origin blog.csdn.net/qq_38563206/article/details/133135784