Advertisement

Make calculator application using python 3

Make calculator application using python 3

If you want to make a calculator application using python, then you are at the right place. Just follow these step and copy paste all the codes given below (same name and extensions as given): Copy this Python code and save it as "calculator.py" in your device.

Python:

 
  
 
import tkinter as tk

def on_click(key):
    if key == "=":
        try:
            result = eval(entry.get())
            entry.delete(0, tk.END)
            entry.insert(tk.END, str(result))
        except:
            entry.delete(0, tk.END)
            entry.insert(tk.END, "Error")
    elif key == "C":
        entry.delete(0, tk.END)
    else:
        entry.insert(tk.END, key)

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

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

row_idx, col_idx = 1, 0
entry = tk.Entry(root, width=20, font=('Arial', 18))
entry.grid(row=0, column=0, columnspan=4)

for button in buttons:
    tk.Button(root, text=button, width=5, height=2,
              command=lambda key=button: on_click(key)).grid(row=row_idx, column=col_idx)
    col_idx += 1
    if col_idx > 3:
        col_idx = 0
        row_idx += 1

root.mainloop()

     
 

Results of the given code is here:

Conclusion:

This code creates a simple calculator using Python's Tkinter library. It defines a function `on_click` to handle button clicks and perform corresponding actions. The calculator interface consists of buttons for numbers, arithmetic operators, and a clear button. When a button is clicked, it inserts the corresponding value into the entry field. The `=` button calculates the result of the expression entered, and the `C` button clears the entry field. Overall, it provides a basic calculator functionality through a graphical user interface.

Post a Comment

0 Comments