Building a Simple Calculator using Tkinter in Python

0


I
ntroduction:
In the world of programming, graphical user interfaces (GUIs) play a pivotal role in creating user-friendly applications. Tkinter, a standard GUI library in Python, provides a simple way to design and develop interactive interfaces. In this tutorial, we'll walk through the process of creating a basic calculator using Tkinter, allowing you to perform arithmetic operations with a few clicks.

rerequisites: Before diving into the tutorial, make sure you have Python installed on your system. Tkinter is included with most Python installations, so you don't need to install it separately.


Step 1: Setting Up the GUI: To begin, import the necessary modules:

import tkinter as tk

Create the main application window:

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

Step 2: Creating Display:

We'll create an Entry widget to display the input and output.

display = tk.Entry(root, width=30, borderwidth=5) display.grid(row=0, column=0, columnspan=4)

Step 3: Define Button Click Function:

Next, we'll define a function to handle button clicks and update the display accordingly.

python
def button_click(number): current = display.get() display.delete(0, tk.END) display.insert(0, current + str(number))

Step 4: Adding Number Buttons: Create buttons for each digit (0-9):

buttons = [ '7', '8', '9', '4', '5', '6', '1', '2', '3', '0' ] row_val = 1 col_val = 0 for button in buttons: tk.Button(root, text=button, padx=20, pady=20, command=lambda btn=button: button_click(btn)).grid(row=row_val, column=col_val) col_val += 1 if col_val > 2: col_val = 0 row_val += 1

Step 5: Adding Operator Buttons: Add buttons for operators (+, -, *, /):


operators = ['+', '-', '*', '/'] row_val = 5 col_val = 0 for operator in operators: tk.Button(root, text=operator, padx=20, pady=20, command=lambda op=operator: button_click(op)).grid(row=row_val, column=col_val) col_val += 1

Step 6: Adding Special Buttons: Include buttons for Clear and Equal (=):

python
tk.Button(root, text='C', padx=20, pady=20, command=lambda: display.delete(0, tk.END)).grid(row=6, column=0) tk.Button(root, text='=', padx=20, pady=20, command=lambda: evaluate()).grid(row=6, column=1, columnspan=2)

Step 7: Implementing Calculation: Define the evaluate function to compute the result and display it:

python
def evaluate(): expression = display.get() try: result = eval(expression) display.delete(0, tk.END) display.insert(0, result) except: display.delete(0, tk.END) display.insert(0, "Error")

Step 8: Run the Application: Finally, start the GUI event loop to display the calculator:

root.mainloop()

Conclusion: In this tutorial, you've learned how to create a simple calculator using the Tkinter library in Python. By following the steps outlined above, you can build a basic GUI calculator that can handle arithmetic operations with ease. Tkinter's simplicity and versatility make it a great choice for developing various graphical applications, and this example serves as a starting point for more complex GUI projects.


SOURCE CODE:👇

from tkinter import *

win = Tk() # This is to create a basic window
win.geometry("312x324")  # this is for the size of the window 
win.resizable(0, 0)  # this is to prevent from resizing the window
win.title("Calculator")

###################Starting with functions ####################
# 'btn_click' function : 
# This Function continuously updates the 
# input field whenever you enter a number

def btn_click(item):
    global expression
    expression = expression + str(item)
    input_text.set(expression)

# 'bt_clear' function :This is used to clear 
# the input field

def bt_clear(): 
    global expression 
    expression = "" 
    input_text.set("")
 
# 'bt_equal':This method calculates the expression 
# present in input field
 
def bt_equal():
    global expression
    result = str(eval(expression)) # 'eval':This function is used to evaluates the string expression directly
    input_text.set(result)
    expression = ""
 
expression = ""
 
# 'StringVar()' :It is used to get the instance of input field
 
input_text = StringVar()
 
# Let us creating a frame for the input field
 
input_frame = Frame(win, width=312, height=50, bd=0, highlightbackground="black", highlightcolor="black", highlightthickness=2)
 
input_frame.pack(side=TOP)
 
#Let us create a input field inside the 'Frame'
 
input_field = Entry(input_frame, font=('arial', 18, 'bold'), textvariable=input_text, width=50, bg="#eee", bd=0, justify=RIGHT)
 
input_field.grid(row=0, column=0)
 
input_field.pack(ipady=10) # 'ipady' is internal padding to increase the height of input field
 
#Let us creating another 'Frame' for the button below the 'input_frame'
 
btns_frame = Frame(win, width=312, height=272.5, bg="grey")
 
btns_frame.pack()
 
# first row
 
clear = Button(btns_frame, text = "C", fg = "black", width = 32, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: bt_clear()).grid(row = 0, column = 0, columnspan = 3, padx = 1, pady = 1)
 
divide = Button(btns_frame, text = "/", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("/")).grid(row = 0, column = 3, padx = 1, pady = 1)
 
# second row
 
seven = Button(btns_frame, text = "7", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(7)).grid(row = 1, column = 0, padx = 1, pady = 1)
 
eight = Button(btns_frame, text = "8", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(8)).grid(row = 1, column = 1, padx = 1, pady = 1)
 
nine = Button(btns_frame, text = "9", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(9)).grid(row = 1, column = 2, padx = 1, pady = 1)
 
multiply = Button(btns_frame, text = "*", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("*")).grid(row = 1, column = 3, padx = 1, pady = 1)
 
# third row
 
four = Button(btns_frame, text = "4", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(4)).grid(row = 2, column = 0, padx = 1, pady = 1)
 
five = Button(btns_frame, text = "5", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(5)).grid(row = 2, column = 1, padx = 1, pady = 1)
 
six = Button(btns_frame, text = "6", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(6)).grid(row = 2, column = 2, padx = 1, pady = 1)
 
minus = Button(btns_frame, text = "-", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("-")).grid(row = 2, column = 3, padx = 1, pady = 1)
 
# fourth row
 
one = Button(btns_frame, text = "1", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(1)).grid(row = 3, column = 0, padx = 1, pady = 1)
 
two = Button(btns_frame, text = "2", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(2)).grid(row = 3, column = 1, padx = 1, pady = 1)
 
three = Button(btns_frame, text = "3", fg = "black", width = 10, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(3)).grid(row = 3, column = 2, padx = 1, pady = 1)
 
plus = Button(btns_frame, text = "+", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click("+")).grid(row = 3, column = 3, padx = 1, pady = 1)
 
# fourth row
 
zero = Button(btns_frame, text = "0", fg = "black", width = 21, height = 3, bd = 0, bg = "#fff", cursor = "hand2", command = lambda: btn_click(0)).grid(row = 4, column = 0, columnspan = 2, padx = 1, pady = 1)
 
point = Button(btns_frame, text = ".", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: btn_click(".")).grid(row = 4, column = 2, padx = 1, pady = 1)
 
equals = Button(btns_frame, text = "=", fg = "black", width = 10, height = 3, bd = 0, bg = "#eee", cursor = "hand2", command = lambda: bt_equal()).grid(row = 4, column = 3, padx = 1, pady = 1)
 
win.mainloop()


Post a Comment

0Comments

Please Select Embedded Mode To show the Comment System.*