Welcome to this tutorial on how to create a calculator using Python and the tkinter library. In this tutorial, we will walk you through the steps to create a simple calculator application with a GUI interface.
Before we begin, make sure you have Python installed on your system. You can download Python from the official website and install it on your machine. We will also be using the tkinter library, which is a built-in library for creating graphical user interfaces in Python.
To start, let’s create a new Python file and import the necessary libraries:
import tkinter as tk
Next, let’s create a class for our calculator application:
class Calculator:
def __init__(self, root):
self.root = root
self.root.title("Simple Calculator")
self.result = ""
self.entry = tk.Entry(self.root, width=20, font=("Helvetica", 16))
self.entry.grid(row=0, column=0, columnspan=4)
buttons = [
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"C", "0", "=", "+"
]
row = 1
col = 0
for button in buttons:
tk.Button(self.root, text=button, width=5, height=2, font=("Helvetica", 12),
command=lambda b=button: self.on_click(b)).grid(row=row, column=col)
col += 1
if col > 3:
col = 0
row += 1
def on_click(self, text):
if text == "C":
self.result = ""
elif text == "=":
try:
self.result = str(eval(self.result))
except:
self.result = "Error"
else:
self.result += text
self.update_entry()
def update_entry(self):
self.entry.delete(0, tk.END)
self.entry.insert(0, self.result)
if __name__ == "__main__":
root = tk.Tk()
app = Calculator(root)
root.mainloop()
In this code snippet, we have defined a class called Calculator
which takes a root
parameter (the main tkinter window) and initializes the GUI for our calculator application. We have created an entry widget for displaying the input and the result, as well as buttons for numbers, arithmetic operations, and the clear and equal sign buttons.
The on_click
method handles the actions when a button is clicked, such as appending the text of the button to the result
string or evaluating the expression when the equal button is clicked. The update_entry
method updates the entry widget with the current result.
To run the calculator application, execute the Python file in your terminal or console:
python calculator.py
You should see a simple calculator GUI with number and operator buttons. You can input numbers and perform arithmetic operations using this calculator.
I hope you found this tutorial helpful. For a more detailed explanation and demonstration, you can check out the full video on our YouTube channel TechnoCloudss and explore more coding tutorials. Happy coding!