Creating a User-Friendly Calculator with Python Using Tkinter – An Easy GUI Project

Posted by


In this tutorial, we will walk through the process of creating a simple calculator using Python and the Tkinter library. Tkinter is a widely used library for creating graphical user interfaces in Python. By the end of this tutorial, you will have a basic understanding of how to create a calculator with basic arithmetic operations such as addition, subtraction, multiplication, and division.

Step 1: Setting up the environment
First, you need to make sure you have Python installed on your computer. You can download Python from the official website (python.org). Once you have Python installed, you can install Tkinter by running the following command in your terminal or command prompt:

pip install tk

Step 2: Creating the GUI
Now that you have Tkinter installed, you can start creating the graphical user interface for your calculator. Create a new Python file and import the necessary libraries:

from tkinter import *

Next, define a function that will handle the button click event:

def on_click(event):
    text = event.widget.cget("text")
    if text == "=":
        try:
            result = str(eval(entry.get()))
            entry.delete(0, END)
            entry.insert(END, result)
        except Exception as e:
            entry.delete(0, END)
            entry.insert(END, "Error")
    elif text == "C":
        entry.delete(0, END)
    else:
        entry.insert(END, text)

# Create the main window
root = Tk()
root.title("Simple Calculator")

# Create an entry widget to display the input and output
entry = Entry(root, width=50, borderwidth=5)
entry.grid(row=0, column=0, columnspan=4)

# Create buttons for numbers and operations
buttons = [
    "7", "8", "9", "/",
    "4", "5", "6", "*",
    "1", "2", "3", "-",
    "C", "0", "=", "+"
]

row = 1
col = 0
for button in buttons:
    btn = Button(root, text=button, padx=20, pady=20)
    btn.grid(row=row, column=col)

    btn.bind("<Button-1>", on_click)

    col += 1
    if col > 3:
        col = 0
        row += 1

# Run the main event loop
root.mainloop()

Step 3: Running the calculator
Save the file and run it using the Python interpreter. You should see a window pop up with a simple calculator interface. You can now perform basic arithmetic operations like addition, subtraction, multiplication, and division. Press the "C" button to clear the input and start a new calculation.

Congratulations! You have successfully created a simple calculator using Python and Tkinter. Feel free to modify the code to add more features and customizations to your calculator. Experiment with different layouts, colors, and functionalities to enhance the user experience. Happy coding!

0 0 votes
Article Rating

Leave a Reply

45 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
45
0
Would love your thoughts, please comment.x
()
x