Building a Simple Calculator with GUI using Tkinter in Python

832102115张馨丹 2023-10-09 17:52:22
The Link Your Classhttps://bbs.csdn.net/forums/ssynkqtd-04?typeId=5171412
The Link of Requirement of This Assignmenthttps://bbs.csdn.net/topics/617332156
The Aim of This AssignmentImplement a visual calculator
MU STU ID and FZU STU ID21127051_832102115

Link to the finished project code: https://github.com/Adandan111/Calculator

Catalogue

  • Introduction
  • 1. PSP(Personal Software Process) form
  • 2. Description of problem-solving ideas.
  • 2.1 Main technologies
  • 2.2 User needs
  • 3.Design and implementation process.
  • 3.1 How the code is organized
  • 3.2 The flow chart of the key functions.
  • 4.Code description
  • Generate executable file
  • 5.Displaying result functions
  • 6.Summarize

Introduction

This blog post documents the process and code for completing a simple visual calculator. It mainly uses Python's GUI library Tkinter to create a simple calculator application. Tkinter provides a set of tools and components for creating GUI applications, including Windows, labels, buttons, text boxes, and more. Finally, use the third-party library Pyinstaller to turn python code into an executable exe file.

1. PSP(Personal Software Process) form

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning6070
• Estimate6070
Development430465
• Analysis3040
• Design Spec1010
• Design Review3035
• Coding Standard1010
• Design5060
• Coding180180
• Code Review6070
• Test6060
Reporting8085
• Test Repor2025
• Size Measurement2020
• Postmortem & Process Improvement Plan4040
Sum570620

2. Description of problem-solving ideas.

2.1 Main technologies

When I started to solve this problem, I first considered whether to use Python's GUI library Tkinter to create this simple visual calculator application. After having this idea, I immediately went to the CSDN official website and Google to search for corresponding information to understand whether this technology could meet the needs of the project, that is, addition, subtraction, multiplication, division, trigonometric functions, and power operations.
Through information search, I confirmed that Tkinter is Python's own GUI library, which is easy to learn and use, and can quickly create simple GUI applications. Moreover, the calculator is a common GUI application that requires the use of buttons, text boxes, event handling and other functions. Tkinter provides the implementation of these functions. In addition, Python's math library provides functions for calculating mathematical operations such as trigonometric functions and π, and is also used in the implementation of calculators. So, I understand this approach works.

2.2 User needs

Next, considering the convenience for users, I decided to convert the calculator into an exe executable file. In this way, users can directly double-click to run without installing the Python environment and related libraries, which is convenient and fast. Moreover, Python provides a variety of third-party libraries, such as PyInstaller, cx_Freeze, etc., which can easily convert Python code into exe executable files without writing complex scripts or command lines. In this assignment, the Pyinstaller library was used.

3.Design and implementation process.

3.1 How the code is organized

This code is organized using the Model-View-Controller (MVC) design pattern. The model is the code that performs the calculations and evaluates the expressions entered by the user. The view is the graphical user interface (GUI) that the user interacts with, which includes the buttons and the display area for the results. The controller is the code that handles the user's input and updates the model and view accordingly.

In this specific implementation, the model is represented by the eval() function that evaluates the mathematical expressions entered by the user. The view is represented by the GUI elements created using the tkinter library, including the buttons and the display area for the results. The controller is represented by the button_click() function that handles the user's input and updates the model and view accordingly.

The code also uses a grid layout to organize the buttons and the display area in a visually appealing way. Additionally, the code uses comments to explain the purpose of each section and function, which improves its readability and maintainability.

3.2 The flow chart of the key functions.

img

4.Code description

Import the tkinter and math modules:

import tkinter as tk
import math

Create the main window:
This part of code creates a main window named root and sets the window title, background color, and size.

root = tk.Tk()
root.title("Simple Calculator")
root.configure(bg="#B8BBDE")
root.geometry("300x400")

Create a text box that displays the results: This part of the code creates a text box to display the calculation results, and sets the size, font and background color of the text box.

result_display = tk.Entry(root, width=20, font=("Helvetica", 32))
result_display.grid(row=0, column=0, columnspan=4, sticky="nsew")
result_display.configure(bg="white")

Set the weight of the grid layout so that the buttons are the same size:

for i in range(2):
    root.grid_rowconfigure(i, weight=1)
    root.grid_columnconfigure(i, weight=1)

Create a button click event:
Here a button click event function button_click is defined, which is used to handle button click events.
If the text content of the button is the equal sign "=", then the content in the current text box will be processed, replacing the exponentiation symbol "^" with "**", and replacing the trigonometric functions with "math.sin", "math.cos ", "math.tan", replace π with the value of math.pi, then use the eval function to calculate the value of the expression, and display the result in the text box. If an exception occurs during calculation, "Error" is displayed in the text box.If the button's text content is "C", clear the content in the text box.If the text content of the button is a left bracket "(" or a right bracket ")", insert the corresponding bracket in the text box. If the button's text content is "π", insert the π symbol in the text box.If the button's text content is another character, insert that character in the text box.

def button_click(event):
    current_text = result_display.get()
    button_text = event.widget.cget("text")

    if button_text == "=":
        try:
            # 替换幂运算符号并计算
            current_text = current_text.replace("^", "**")
            # 替换三角函数并计算
            current_text = current_text.replace("sin", "math.sin")
            current_text = current_text.replace("cos", "math.cos")
            current_text = current_text.replace("tan", "math.tan")
            # 替换π
            current_text = current_text.replace("π", str(math.pi))
            result = eval(current_text)
            result_display.delete(0, tk.END)
            result_display.insert(tk.END, str(result))
        except Exception as e:
            result_display.delete(0, tk.END)
            result_display.insert(tk.END, "错误")
    elif button_text == "C":
        result_display.delete(0, tk.END)
    elif button_text in ["(", ")"]:
        result_display.insert(tk.END, button_text)
    elif button_text == "π":
        result_display.insert(tk.END, "π")
    else:
        result_display.insert(tk.END, button_text)

Creating buttons: Here a list of buttons containing all the button characters is created and all the buttons are created using a loop. Each button is bound to the click event button_click, and the background color of the button is set.

buttons = [
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    '0', '.', '=', '+',
    'C',
    'sin', 'cos', 'tan', '^',
    '(', ')',
    'π'
]

row, col = 1, 0
for button_text in buttons:
    button = tk.Button(root, text=button_text, font=("Helvetica", 20))
    button.grid(row=row, column=col, sticky="nsew")
    col += 1
    if col > 3:
        col = 0
        row += 1

    button.bind("<Button-1>", button_click)
    button.configure(bg="#E6E6FA")

Finally, run the application and enter the main loop, waiting for user interaction:

root.mainloop()

Generate executable file

Create a spec file:

pyinstaller --onefile calculator1.py

Generate executable file:

pyinstaller calculator1.spec

After executing the above command, PyInstaller will automatically package the code into an executable file and save the executable file in the dist directory.

The complete code is as follows:

import tkinter as tk
import math
# 导入了 tkinter 模块用于创建 GUI 界面,以及 math 模块用于执行数学运算。

# 创建主窗口
root = tk.Tk()
root.title("Simple Calculator")
root.configure(bg="#B8BBDE")  # 设置窗口背景颜色

# 设置主窗口大小
root.geometry("300x400")

# 创建显示结果的文本框
result_display = tk.Entry(root, width=20, font=("Helvetica", 32))
result_display.grid(row=0, column=0, columnspan=4, sticky="nsew")
result_display.configure(bg="white")  # 设置文本框背景颜色

# 设置网格布局的权重,使按钮大小相同
for i in range(2):
    root.grid_rowconfigure(i, weight=1)
    root.grid_columnconfigure(i, weight=1)

# 创建按钮点击事件
def button_click(event):
    current_text = result_display.get()
    button_text = event.widget.cget("text")

    if button_text == "=":
        try:
            # 替换幂运算符号并计算
            current_text = current_text.replace("^", "**")
            # 替换三角函数并计算
            current_text = current_text.replace("sin", "math.sin")
            current_text = current_text.replace("cos", "math.cos")
            current_text = current_text.replace("tan", "math.tan")
            # 替换π
            current_text = current_text.replace("π", str(math.pi))
            result = eval(current_text)
            result_display.delete(0, tk.END)
            result_display.insert(tk.END, str(result))
        except Exception as e:
            result_display.delete(0, tk.END)
            result_display.insert(tk.END, "错误")
    elif button_text == "C":
        result_display.delete(0, tk.END)
    elif button_text in ["(", ")"]:
        result_display.insert(tk.END, button_text)
    elif button_text == "π":
        result_display.insert(tk.END, "π")
    else:
        result_display.insert(tk.END, button_text)

# 创建按钮
buttons = [
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    '0', '.', '=', '+',
    'C',
    'sin', 'cos', 'tan', '^',  # 添加三角函数和幂运算按钮
    '(', ')',  # 添加左右括号按钮
    'π'  # 添加π按钮
]

row, col = 1, 0
for button_text in buttons:
    button = tk.Button(root, text=button_text, font=("Helvetica", 20))
    button.grid(row=row, column=col, sticky="nsew")
    col += 1
    if col > 3:
        col = 0
        row += 1

    button.bind("<Button-1>", button_click)
    button.configure(bg="#E6E6FA")  # 设置按钮背景颜色

# 运行应用程序
root.mainloop()

5.Displaying result functions

img

In the above gif, I show addition, subtraction, multiplication and division, trigonometric functions, power operations, and the situation when there is an error in the input.

6.Summarize

Through this assignment, I mastered how to use Python's built-in tkinter module to quickly create a GUI interface and implement basic arithmetic operations. The code is simple and easy to understand, the logic is clear, and it is easy to maintain.
However, I also realize that there are still areas that can be improved in this assignment. In the future, I plan to add more calculation functions, such as logarithmic functions. And the history record function makes it convenient for users to view and manage.

...全文
168 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
内容概要:本文深入探讨了DMA高效数据传输实现方案在高性能计算芯片领域的应用与架构创新,重点分析了缓存一致性DMA、多通道DMA架构及其在数据中心SmartNIC、存算一体芯片和Chiplet互连等场景中的实践。文章结合RISC-V架构,通过Chisel硬件描述语言和C语言驱动代码,展示了多通道DMA控制器的设计与实现,涵盖仲裁机制、AXI总线适配、分散-聚集传输模式及中断处理等核心技术,并强调了性能优化与验证方法。最后展望了AI调度、光互连、近存计算与安全DMA等未来发展方向。; 适合人群:具备数字电路与计算机体系结构基础,从事芯片设计、嵌入式开发或高性能计算相关工作的研发人员,尤其是有1-5年经验的工程师与研究人员。; 使用场景及目标:①理解DMA在突破“内存墙”和降低系统能耗中的关键技术路径;②掌握多通道DMA控制器的硬件设计与驱动开发方法;③应用于SmartNIC、AI加速器、Chiplet等高性能芯片系统的数据传输架构设计;④为构建高带宽、低延迟、高能效的异构计算平台提供参考。; 阅读建议:此资源融合硬件设计与软件驱动,建议结合Chisel仿真与RISC-V平台实操,重点关注DMA与缓存一致性、异构计算单元的协同机制,并通过性能计数器与错误注入手段进行系统级验证。
内容概要:本文围绕基于共享储能服务的智能楼宇双层优化配置展开研究,通过Matlab代码实现相应的数学建模与仿真分析,提出一种结合上层规划与下层运行的协同优化框架,旨在提升智能楼宇能源系统的经济性、能效水平与电网互动能力。研究充分考虑光伏发电、负荷需求、储能充放电等多元因素,采用先进的优化算法(如智能优化算法)对共享储能资源的容量配置与运行调度进行精细化决策,有效降低用能成本,提高可再生能源消纳率,并增强系统运行的稳定性与灵活性。全文涵盖模型构建、算法设计、求解流程及结果验证,具备较高的理论深度与工程应用价值; 适合人群:具备电力系统、能源管理、优化算法等相关背景的科研人员、研究生,以及从事智能电网、综合能源系统、建筑节能等领域的工程技术人员; 使用场景及目标:①用于智能楼宇及园区级能源系统的规划与运行优化研究;②支撑共享储能机制下的资源配置、经济调度与商业模式设计;③作为Matlab仿真教学与高水平论文复现的典型案例,帮助深入理解双层优化模型、主从博弈结构及智能算法在能源系统中的应用; 阅读建议:建议结合提供的Matlab代码进行同步学习与调试,重点关注上下层模型的耦合关系与迭代求解过程,可进一步拓展至多主体协同、不确定性建模(如风光出力波动)及鲁棒优化等前沿方向开展深化研究。
内容概要:本文《【故障检测】基于 KPCA 的故障检测【T2 和 Q 统计指数的可视化】(Matlab代码实现)》系统阐述了基于核主成分分析(KPCA)的非线性故障检测方法,重点实现了T²和Q统计量的构建与可视化过程。通过Matlab编程,将高维非线性数据映射至特征空间,提取主成分并建立监控模型,利用T²和Q指数对工业过程中的异常状态进行联合监测与诊断,有效提升了复杂系统中早期故障的识别能力,具有较强的工程实用性与理论参考价值。; 适合人群:适用于具备信号处理、控制工程或工业过程监测背景,熟悉Matlab编程语言,并从事故障诊断、智能运维、自动化系统研发等相关工作的研究生、科研人员及工程技术开发者。; 使用场景及目标:①应用于化工、电力、制造等流程工业中的关键设备状态监控与早期故障预警;②作为学术研究中KPCA算法的仿真验证平台,用于对比分析不同非线性降维方法的检测性能;③深化对非线性过程监控中统计指标设计与阈值判定机制的理解与实践应用。; 阅读建议:建议读者结合所提供的Matlab代码逐模块运行与调试,深入掌握KPCA建模流程、主成分子空间划分及T²、Q统计量的计算逻辑,鼓励在标准数据集(如TE过程)上复现实验结果,并尝试扩展至其他非线性场景以提升模型泛化能力。

176

社区成员

发帖
与我相关
我的任务
社区描述
梅努斯软件工程
软件工程 高校 福建省·福州市
社区管理员
  • LinQF39
  • Jcandc
  • chjinhuu
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧