Python Code for Calculator using Tkinter

Posted by

Python Calculator using Tkinter

Python Calculator using Tkinter

In this article, we will create a simple calculator using Python and Tkinter. Tkinter is a popular GUI toolkit for Python and it is simple to use.

Python Code:

        
            from tkinter import *

            def click(event):
                text = event.widget.cget("text")

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

            root = Tk()
            root.geometry("400x500")
            root.title("Calculator")

            entry = Entry(root, font="Arial 15")
            entry.pack(expand=True, fill="both")

            buttons = [
                "7", "8", "9", "/",
                "4", "5", "6", "*",
                "1", "2", "3", "-",
                "C", "0", "=", "+"
            ]

            for i in range(4):
                frame = Frame(root)
                frame.pack(expand=True, fill="both")

                for j in range(4):
                    button = Button(frame, text=buttons[i*4 + j], font="Arial 15")
                    button.pack(side=LEFT, expand=True, fill="both")
                    button.bind("", click)

            root.mainloop()
        
    

This Python code creates a simple calculator GUI using Tkinter. It defines a function click that handles button click events and performs the appropriate calculation based on the button clicked.

The root object is the main window of the calculator with a text entry field and buttons for numbers and operations. The calculator supports basic arithmetic operations such as addition, subtraction, multiplication, and division.

Try running this code in your Python environment and you will have a simple calculator application ready to use!