Python is a versatile and powerful programming language that can be used for many applications, including creating a calculator. In this blog post, we will learn how to create a simple calculator using Python that can perform basic arithmetic operations such as addition, subtraction, multiplication and division.
To create a calculator using Python, we will need to use some built-in modules and functions. The modules we will use are:
- sys: This module provides access to some system-specific parameters and functions, such as command-line arguments and exit status.
- math: This module provides access to some mathematical functions and constants, such as pi and square root.
- tkinter: This module provides a graphical user interface (GUI) toolkit for Python, which allows us to create windows, buttons, labels and other widgets.
The functions we will use are:
- eval: This function evaluates a string as a Python expression and returns the result. For example, eval("2+3") returns 5.
- str: This function converts any object to a string representation. For example, str(5) returns "5".
- lambda: This is a keyword that allows us to create anonymous functions, which are functions that are not bound to a name. For example, lambda x: x+1 is a function that takes one argument x and returns x+1.
The steps we will follow to create a calculator using Python are:
1. Import the modules we need.
2. Create a window using tkinter and give it a title and a size.
3. Create a label widget to display the expression and the result of the calculation.
4. Create a string variable to store the expression entered by the user.
5. Create a function to update the label with the expression and the result.
6. Create a function to clear the expression and the result.
7. Create a function to append a character to the expression.
8. Create a function to evaluate the expression and display the result.
9. Create buttons for each digit, operator and function (clear and equal) and bind them to their respective functions.
10. Arrange the widgets in a grid layout using tkinter.
python
# Import modules
import sys
import math
import tkinter as tk
# Create window
window = tk.Tk()
window.title("Calculator")
window.geometry("300x300")
# Create label
label = tk.Label(window, text="0", font=("Arial", 20))
label.grid(row=0, column=0, columnspan=4)
# Create string variable
expression = tk.StringVar()
expression.set("")
# Create update function
def update():
# Get the expression
expr = expression.get()
# Try to evaluate the expression
try:
# Evaluate the expression using eval function
result = eval(expr)
# Update the label with the expression and the result
label.config(text=expr + "\n" + str(result))
# If there is an error, display it
except Exception as e:
# Update the label with the error message
label.config(text=str(e))
# Create clear function
def clear():
# Clear the expression
expression.set("")
# Update the label
update()
# Create append function
def append(char):
# Get the current expression
expr = expression.get()
# Append the character to the expression
expr += char
# Set the new expression
expression.set(expr)
# Update the label
update()
# Create evaluate function
def evaluate():
# Get the current expression
expr = expression.get()
# Try to evaluate the expression
try:
# Evaluate the expression using eval function
result = eval(expr)
# Set the new expression as the result
expression.set(str(result))
# Update the label
update()
# If there is an error, display it
except Exception as e:
# Update the label with the error message
label.config(text=str(e))
# Create buttons
buttons = [
["7", "8", "9", "+"],
["4", "5", "6", "-"],
["1", "2", "3", "*"],
["0", ".", "C", "/"],
["(", ")", "=", "exit"]
]
# Loop through buttons and create them
for i in range(len(buttons)):
for j in range(len(buttons[i])):
# Get the button text
text = buttons[i][j]
# Create a button with the text and a size of 5x2
button = tk.Button(window, text=text, width=5, height=2)
# Place the button in the grid layout at row i+1 and column j
button.grid(row=i+1, column=j)
# Bind different functions to different buttons
if text == "C":
# Bind the clear function to the button
button.config(command=clear)
elif text == "=":
# Bind the evaluate function to the button
button.config(command=evaluate)
elif text == "exit":
# Bind the exit function to the button
button.config(command=sys.exit)
else:
# Bind the append function with the text as an argument to the button
button.config(command=lambda char=text: append(char))
# Start the main loop of the window
window.mainloop()
Comments
Post a Comment