Write a calculator in Python

Posted by Rojay on Wed, 16 Feb 2022 12:06:03 +0100

Source code in python learning exchange q group: 733089476

preface

There are two common computing AIDS. One is the abacus invented by the ancients, and the other is the calculator invented by our modern people. Compared with the abacus, the calculator is better than the abacus in terms of convenience and computing speed. In this paper, we use Python to implement a simple calculator.

realization

Almost everyone of us has used calculators. We should all be familiar with calculators. Calculators are relatively simple as a whole, mainly including: display, keyboard, logical processing of operation, etc. we use tkinter library to realize the graphical interface of calculators. Let's take a look at the specific implementation process below.

First, we draw a main window. The code is as follows:

# Create main window
tk = tkinter.Tk()
# Set window size and position
tk.geometry('300x210+500+200')
# Changing the window size is not allowed
tk.resizable(False, False)
# Set window title
tk.title('Calculator')

Take a look at the effect:

We then draw the display, and the code is as follows:

# Automatically refresh string variables. You can use set and get methods to transfer values and take values
contentVar = tkinter.StringVar(tk, '')
# Create a single line text box
contentEntry = tkinter.Entry(tk, textvariable=contentVar)
# Set the text box to read-only
contentEntry['state'] = 'readonly'
# Set the coordinates, width and height of the text box
contentEntry.place(x=20, y=10, width=260, height=30)

Take a look at the effect:

Then draw the keyboard, and the code is as follows:

# Button display content
bvalue = ['C', '+', '-', '//', '2', '0', '1', '√', '3', '4', '5', '*', '6', '7', '8', '.', '9', '/', '**', '=']
index = 0
# Place the button 5x4
for row in range(5):
    for col in range(4):
        d = bvalue[index]
        index += 1
        btnDigit = tkinter.Button(tk, text=d, command=lambda x=d: onclick(x))
        btnDigit.place(x=20 + col * 70, y=50 + row * 30, width=50, height=20)

Take a look at the effect:

After drawing the interface, let's take a look at the code for processing operation logic, as shown below:

# Click event
def onclick(btn):
    # operator
    operation = ('+', '-', '*', '/', '**', '//')
    # Gets the content in the text box
    content = contentVar.get()
    # If the existing content starts with a decimal point, add 0 before it
    if content.startswith('.'):
        content = '0' + content  # Strings can be added with + directly
    # React differently according to different buttons
    if btn in '0123456789':
        # Press 0-9 to append in content
        content += btn
    elif btn == '.':
        # Separate content from + - * / characters
        lastPart = re.split(r'\+|-|\*|/', content)[-1]
        if '.' in lastPart:
            # Information prompt dialog box
            tkinter.messagebox.showerror('error', 'Recurring decimal point')
            return
        else:
            content += btn
    elif btn == 'C':
        # Clear text box
        content = ''
    elif btn == '=':
        try:
            # Evaluate the entered expression
            content = str(eval(content))
        except:
            tkinter.messagebox.showerror('error', 'Incorrect expression')
            return
    elif btn in operation:
        if content.endswith(operation):
            tkinter.messagebox.showerror('error', 'Continuous operators are not allowed')
            return
        content += btn
    elif btn == '√':
        # From n is a list
        n = content.split('.')
        # If all the numbers in the list are numbers, it is to check whether the expression is correct
        if all(map(lambda x: x.isdigit(), n)):
            content = eval(content) ** 0.5
        else:
            tkinter.messagebox.showerror('error', 'Expression error')
            return
    # Displays the results in a text box
    contentVar.set(content)

After the overall implementation, let's demonstrate and see the effect:

pack

To make it easier to use, we can package Python code into an exe file. We can use pyinstaller and use pip install pyinstaller command for installation.

When packaging, we use pyinstaller -- onefile -- nonwindowed counter Py command is enough. At this time, the file generated by packaging is the default icon. If we want to specify our own icon, we can add the parameter -- icon="xxx\xxx.ico". The file generated by packaging is in dist directory, as shown in the following figure:

At this point, we just run the exe file directly.

summary

In this paper, we use Python to implement a simple calculator. If you are interested, you can try to add more functions and personalize the keyboard.

Source code in python learning exchange q group: 733089476

Topics: Python pygame