EE301_A1_Caculator

Student’s information

The Link Your Classhttps://bbs.csdn.net/forums/ssynkqtd-04
The Link of Requirement of This Assignmenthttps://bbs.csdn.net/topics/617332156
The Aim of This AssignmentCreate a calculator with a visual interface.
MU STU ID and FZU STU ID21125864_832101112

Github link

All the code is open source, the following is the Github link:

https://github.com/Asmund-Fan/simple_calculator


Catalogue

I. Introduction

II. PSP form

III. Description of problem-solving ideas

1. Problem restatement

2. Problem analysis

IV. Design and implementation process

1. GUI creation

2. Input and output

3. Click function

4. Arithmetic function

5. Reset and back operation

6. The flow chart

V.  Code description 

1. Import module

2. Layout window

 3. Set display frame

4. Set buttons

5. Wrapper function

i. Click

ii. Calculation(add, subtract, multiply, divide and exponentiation)

iii. Trigonometric functions

iv. Reset

v.  Back

6. Equip the function to the button

7. Set the main loop

VI. Displaying result

VII. Summary


I. Introduction

This blog is about how to create a simple calculator with a visual interface using Python code. In this blog, I'll cover the description of problem-solving ideas, the design and implementation process, the code description, and a demonstration video for this simple calculator. The development steps and design ideas of the code are introduced in detail.

II. PSP form

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning 3025
• Estimate3025
Development210190
• Analysis1520
• Design Spec3025
• Design Review1010
• Coding Standard1510
• Design2025
• Coding6070
• Code Review2010
• Test4020
Reporting4055
• Test Repor1015
• Size Measurement1016
• Postmortem & Process Improvement Plan2025
Sum 280270

III. Description of problem-solving ideas

1. Problem restatement

      The calculator designed by this blog mainly meets the following two needs:

          ① Basic requirement: Implement addition, subtraction, multiplication, division, and clear functions.

          ② Advanced requirement: Implement functionality for exponentiation, trigonometric functions, and more.

2. Problem analysis

      When it comes to designing the user interface and interaction for this calculator application, the primary task is to ensure a user-friendly and seamless user experience. The user interface should allow users to easily input numbers, perform operations, and display the calculation results clearly. Simultaneously, we must carry out input validation to ensure that the data entered by users is valid.

      In terms of calculation logic and implementation, we need to design the underlying logic of the calculator, including how various mathematical operations and function calculations are performed. This may require the use of algorithms and mathematical libraries to ensure the accuracy and efficiency of calculations. Finally, we need to write code to implement all the functionalities of the calculator, including the user interface, error handling, and mathematical operation logic. Through careful design and implementation, we can provide users with a powerful and user-friendly calculator application.

IV. Design and implementation process

1. GUI creation

       I chose to use python's tkinter module to create the GUI. With the tkinter module, I can easily set the GUI size, color, etc. The following numbers and arithmetic functions will be implemented and displayed on the GUI.

Tkinter module is Python standard TK GUI toolkit interface, can achieve some relatively simple GUI creation. The reasons for choosing the tkinter module are as follows:

    ① Tkinter module is fully functional;

    ② Faster running speed;

    ③ When developing, the statements used are shorter and more understandable.

2. Input and output

      ○ I set the buttons to input the numbers and arithmetic functions. Because this can avoid illegal symbol input. 

      ○ In addition, I set up a Label to display the input information and results of the calculator.

3. Click function

      ○  Through a custom function, the click status and record of the button are displayed on the Label.

4. Arithmetic function

      ○ For basic operations and exponentiation, by reading the click record of a button, the string expression of the read click record is converted to the result of the expression by the eval() function.

      ○ For trigonometric functions, by reading the click record of the button, the eval() function is used to obtain the result of the previous click record, and then the math module is used to perform trigonometric operations on the result of the operation, and finally the output result is obtained.

      ○ If there is an illegal string expression during the calculation process, the operation stops and the output is "error".

5. Reset and back operation

      ○ For the reset operation, clear the record and return an empty character to the Label.

      ○ For the back operation, by the operation of the list, the last character is ignored and the remaining characters are returned to the Label.

6. The flow chart

      The following is a rough flow chart of the simple calculator:

V.  Code description 

1. Import module

Import the tkinter and math modules

from tkinter import *
import math

2. Layout window

Lay out a window and set its size, transparency, and background color.

# Create main window
root = Tk()

# Set application name
root.title('Calculator')
# Set window size
root.geometry('215x250+150+150')
# Set window transparency
root.attributes("-alpha", 0.9)
# Set the main window background color
root["background"] = "#ffffff"

Hint:

The geometry method takes a string argument and sets the width and height of the program and the xy coordinates in the upper left corner. The width and height must be connected with a lowercase letter x, and other data must be connected with a + sign.

 3. Set display frame

Set a Label to display the click record and the result.

# Sets a StringVar variable
result_num = StringVar()
# Initialize a character whose result_num is empty
result_num.set('')

# Set a Label to display the value of result_num, and set the size of the Label
Label(root,
      textvariable=result_num, height=2, width=29, justify=LEFT, anchor=SE
      ).grid(row=1,column=1, columnspan=4)

4. Set buttons

Sets the color, position, and label of the buttons.

# Set the first row button
button_reset=Button(root, text='C', width=5, relief=FLAT, background="#b1b2b2")
button_back=Button(root, text='←', width=5, relief=FLAT, background="#b1b2b2")
button_division=Button(root, text='÷', width=5, relief=FLAT, background="#b1b2b2")
button_multiplication=Button(root, text='x', width=5, relief=FLAT, background="#b1b2b2")
button_reset.grid(row=2, column=1, padx=4, pady=2)
button_back.grid(row=2, column=2, padx=4, pady=2)
button_division.grid(row=2, column=3, padx=4, pady=2)
button_multiplication.grid(row=2, column=4, padx=4, pady=2)

# Set the second row button
button_7=Button(root, text='7', width=5, relief=FLAT, background="#eacda1")
button_8=Button(root, text='8', width=5, relief=FLAT, background="#eacda1")
button_9=Button(root, text='9', width=5, relief=FLAT, background="#eacda1")
button_subtraction=Button(root, text='-', width=5, relief=FLAT, background="#b1b2b2")
button_7.grid(row=3, column=1, padx=4, pady=2)
button_8.grid(row=3, column=2, padx=4, pady=2)
button_9.grid(row=3, column=3, padx=4, pady=2)
button_subtraction.grid(row=3, column=4, padx=4, pady=2)

#Set the third row button
button_4=Button(root, text='4', width=5, relief=FLAT, background="#eacda1")
button_5=Button(root, text='5', width=5, relief=FLAT, background="#eacda1")
button_6=Button(root, text='6', width=5, relief=FLAT, background="#eacda1")
button_pluss=Button(root, text='+', width=5, relief=FLAT, background="#b1b2b2")
button_4.grid(row=4, column=1, padx=4, pady=2)
button_5.grid(row=4, column=2, padx=4, pady=2)
button_6.grid(row=4, column=3, padx=4, pady=2)
button_pluss.grid(row=4, column=4, padx=4, pady=2)

# Set the fourth row button
button_1=Button(root, text='1', width=5, relief=FLAT, background="#eacda1")
button_2=Button(root, text='2', width=5, relief=FLAT, background="#eacda1")
button_3=Button(root, text='3', width=5, relief=FLAT, background="#eacda1")
button_equal=Button(root, text='=', width=5, height=3, relief=FLAT, background="#b1b2b2")
button_1.grid(row=5, column=1, padx=4, pady=2)
button_2.grid(row=5, column=2, padx=4, pady=2)
button_3.grid(row=5, column=3, padx=4, pady=2)
button_equal.grid(row=5, column=4, padx=4, pady=2, rowspan=2)

#Set the fifth row button
button_0=Button(root, text='0', width=13, relief=FLAT, background="#eacda1")
button_dot=Button(root, text='.', width=5, relief=FLAT, background="#eacda1")
button_0.grid(row=6, column=1, padx=4, pady=2, columnspan=2)
button_dot.grid(row=6, column=3, padx=4, pady=2)

# Set the sixth row button
button_exp=Button(root, text='^', width=5, relief=FLAT, background="#b1b2b2")
button_cos=Button(root, text='cos', width=5, relief=FLAT, background="#b1b2b2")
button_sin=Button(root, text='sin', width=5, relief=FLAT, background="#b1b2b2")
button_tan=Button(root, text='tan', width=5, relief=FLAT, background="#b1b2b2")
button_exp.grid(row=7, column=1, padx=4, pady=2)
button_cos.grid(row=7, column=2, padx=4, pady=2)
button_sin.grid(row=7, column=3, padx=4, pady=2)
button_tan.grid(row=7, column=4, padx=4, pady=2)

5. Wrapper function

i. Click

Get clicks and record click history.

def click(x):
    result_num.set(result_num.get() + x)

ii. Calculation(add, subtract, multiply, divide and exponentiation)

Calculate the result using the eval() function.

def calculation():
    try:
        # read record
        opt_str = result_num.get()
        # calculation
        result = eval(opt_str)
        # display the output
        result_num.set(str(result))
    except:
        # display "error"
        result_num.set("error")

iii. Trigonometric functions

The calculation of the trigonometric function is similar to that of the calculation function, but the calculation of the corresponding trigonometric function is added.

  (1) Cosine calculation

def cosine():
    try:
        opt_str = result_num.get()
        result = eval(opt_str)
        result_num.set(math.cos(result))
    except:
        result_num.set("error")

  (2) Sine calculation

def sine():
    try:
        opt_str = result_num.get()
        result = eval(opt_str)
        result_num.set(math.sin(result))
    except:
        result_num.set("error")

  (3) Tangent calculation

def tangent():
    try:
        opt_str = result_num.get()
        result = eval(opt_str)
        result_num.set(math.tan(result))
    except:
        result_num.set("error")

iv. Reset

The reset function is to empty the click record and return an empty character.

def reset():
    result_num.set('')

v.  Back

The back function deletes the characters in the click record by the operation of the list.

def back():
    temp_equ = result_num.get()
    result_num.set(temp_equ[:-1])

6. Equip the function to the button

Associate buttons with functions.

button_1.config(command=lambda: click('1'))
button_2.config(command=lambda: click('2'))
button_3.config(command=lambda: click('3'))
button_4.config(command=lambda: click('4'))
button_5.config(command=lambda: click('5'))
button_6.config(command=lambda: click('6'))
button_7.config(command=lambda: click('7'))
button_8.config(command=lambda: click('8'))
button_9.config(command=lambda: click('9'))
button_0.config(command=lambda: click('0'))
button_pluss.config(command=lambda: click('+'))
button_subtraction.config(command=lambda: click('-'))
button_multiplication.config(command=lambda: click('*'))
button_division.config(command=lambda: click('/'))
button_dot.config(command=lambda: click('.'))
button_equal.config(command=calculation)
button_reset.config(command=reset)
button_back.config(command=back)
button_exp.config(command=lambda: click('**'))
button_cos.config(command=cosine)
button_sin.config(command=sine)
button_tan.config(command=tangent)

7. Set the main loop

Set the main loop to run the program continuously

# Set the main loop
root.mainloop()  

VI. Displaying result

Here's a demo video of the code:

demo video

VII. Summary

In this blog, I use python's library functions to build a GUI to implement the functionality of a simple calculator. The calculator not only realizes basic functions such as addition, subtraction, multiplication and division, but also realizes exponential operation and trigonometric function calculation. Although the implementation code is simple, it accomplishes the task requirements efficiently.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值