Creating a Basic Calculator Application with Tkinter in Python

Posted by

Simple Calculator App using Tkinter in Python

Simple Calculator App using Tkinter in Python

In this tutorial, we will create a simple calculator app using Tkinter library in Python. Tkinter is a standard GUI toolkit for Python that allows you to create interactive applications with graphical user interfaces.

Step 1: Install Tkinter

If you haven’t already installed Tkinter, you can do so by running the following command:

    pip install tk
    

Step 2: Create the GUI

Now, let’s create a simple calculator app by defining the GUI elements such as buttons, entry widget, and labels:

    
    import tkinter as tk

    def click(event):
        global expression
        expression = expression + event.widget.cget("text")
        input_text.set(expression)

    def clear():
        global expression
        expression = ""
        input_text.set("")

    def calculate():
        try:
            result = str(eval(expression))
            input_text.set(result)
            expression = result
        except:
            input_text.set("Error")
            expression = ""

    root = tk.Tk()
    root.title("Simple Calculator")

    input_text = tk.StringVar()
    expression = ""

    entry = tk.Entry(root, textvariable=input_text, font=('Helvetica', 15))
    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 btn in buttons:
        button = tk.Button(root, text=btn, font=('Helvetica', 15))
        button.grid(row=row, column=col, padx=5, pady=5)
        button.bind("", click)
        col += 1
        if col > 3:
            col = 0
            row += 1

    clear_button = tk.Button(root, text="Clear", font=('Helvetica', 15), command=clear)
    clear_button.grid(row=row, column=0, columnspan=4)
    
    root.mainloop()
    
    

Now you should have a simple calculator app with basic functionalities like addition, subtraction, multiplication, and division. You can further enhance the app by adding more features and functionalities.

Conclusion

In this tutorial, we have learned how to create a simple calculator app using Tkinter library in Python. You can customize the app and add more functionalities to make it more advanced. Happy coding!