Building a Simple Calculator using Tkinter in Python
Author -
Code with Yush
August 14, 2023
0
Introduction: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.
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