Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Turtle
  • Python PIL
  • Python Program
  • Python Projects
  • Python DataBase
  • Python Flask
  • Python Django
  • Numpy
  • Pandas
  • Python Database
  • Data Science With Python
  • Machine Learning with Python
  • Django
  • Flask
  • R
Open In App
Next Article:
Python Tutorial | Learn Python Programming Language
Next article icon

Python | Simple calculator using Tkinter

Last Updated : 15 Jul, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite : Tkinter Introduction
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.
Let’s see how to create a basic calculator using Tkinter. 

Basic steps: 

  • First we create an object named root out of tk.
  • We create an object of the calc and pass root as master to the init method.
  • Mainloop starts an event loop, which is basically an infinite loop waiting for events and respond accordingly. The mainloop can be terminated by closing the window or using close method.

Below is the implementation: 

Python3




# importing Tkinter and math
from tkinter import *
import math
 
# calc class
class calc:
 
    def getandreplace(self):
 
        """replace x with * and ÷ with /"""
        self.expression = self.e.get()
        self.newtext=self.expression.replace('/','/')
        self.newtext=self.newtext.replace('x','*')
 
 
    def equals(self):
        """when the equal button is pressed"""
        self.getandreplace()
        try:
            # evaluate the expression using the eval function
            self.value= eval(self.newtext)
        except SyntaxError or NameError:
            self.e.delete(0,END)
            self.e.insert(0,'Invalid Input!')
        else:
            self.e.delete(0,END)
            self.e.insert(0,self.value)
 
    def squareroot(self):
        """squareroot method"""
        self.getandreplace()
        try:
            # evaluate the expression using the eval function
            self.value= eval(self.newtext)
        except SyntaxError or NameError:
            self.e.delete(0,END)
            self.e.insert(0,'Invalid Input!')
        else:
            self.sqrtval=math.sqrt(self.value)
            self.e.delete(0,END)
            self.e.insert(0,self.sqrtval)
 
    def square(self):
        """square method"""
        self.getandreplace()
        try:
            #evaluate the expression using the eval function
            self.value= eval(self.newtext)
        except SyntaxError or NameError:
            self.e.delete(0,END)
            self.e.insert(0,'Invalid Input!')
        else:
            self.sqval=math.pow(self.value,2)
            self.e.delete(0,END)
            self.e.insert(0,self.sqval)
 
    def clearall(self):
            """when clear button is pressed,clears the text input area"""
            self.e.delete(0,END)
 
    def clear1(self):
            self.txt=self.e.get()[:-1]
            self.e.delete(0,END)
            self.e.insert(0,self.txt)
 
    def action(self,argi):
            """pressed button's value is inserted into the end of the text area"""
            self.e.insert(END,argi)
 
    def __init__(self,master):
            """Constructor method"""
            master.title('Calculator')
            master.geometry()
            self.e = Entry(master)
            self.e.grid(row=0,column=0,columnspan=6,pady=3)
            self.e.focus_set() #Sets focus on the input text area
 
            # Generating Buttons
            Button(master,text="=",width=11,height=3,fg="blue",
                   bg="orange",command=lambda:self.equals()).grid(
                                     row=4, column=4,columnspan=2)
 
            Button(master,text='AC',width=5,height=3,
                          fg="red", bg="light green",
             command=lambda:self.clearall()).grid(row=1, column=4)
 
            Button(master,text='C',width=5,height=3,
                   fg="red",bg="light green",
                   command=lambda:self.clear1()).grid(row=1, column=5)
 
            Button(master,text="+",width=5,height=3,
                   fg="blue",bg="orange",
                   command=lambda:self.action('+')).grid(row=4, column=3)
 
            Button(master,text="x",width=5,height=3,
                    fg="blue",bg="orange",
                    command=lambda:self.action('x')).grid(row=2, column=3)
 
            Button(master,text="-",width=5,height=3,
                    fg="red",bg="light green",
                    command=lambda:self.action('-')).grid(row=3, column=3)
 
            Button(master,text="÷",width=5,height=3,
                   fg="blue",bg="orange",
                   command=lambda:self.action('/')).grid(row=1, column=3)
 
            Button(master,text="%",width=5,height=3,
                   fg="red",bg="light green",
                   command=lambda:self.action('%')).grid(row=4, column=2)
 
            Button(master,text="7",width=5,height=3,
                   fg="blue",bg="orange",
                   command=lambda:self.action('7')).grid(row=1, column=0)
 
            Button(master,text="8",width=5,height=3,
                   fg="red",bg="light green",
                   command=lambda:self.action(8)).grid(row=1, column=1)
 
            Button(master,text="9",width=5,height=3,
                   fg="blue",bg="orange",
                   command=lambda:self.action(9)).grid(row=1, column=2)
 
            Button(master,text="4",width=5,height=3,
                   fg="red",bg="light green",
                   command=lambda:self.action(4)).grid(row=2, column=0)
 
            Button(master,text="5",width=5,height=3,
                   fg="blue",bg="orange",
                   command=lambda:self.action(5)).grid(row=2, column=1)
 
            Button(master,text="6",width=5,height=3,
                   fg="white",bg="blue",
                   command=lambda:self.action(6)).grid(row=2, column=2)
 
            Button(master,text="1",width=5,height=3,
                   fg="red",bg="light green",
                   command=lambda:self.action(1)).grid(row=3, column=0)
 
            Button(master,text="2",width=5,height=3,
                   fg="blue",bg="orange",
                   command=lambda:self.action(2)).grid(row=3, column=1)
 
            Button(master,text="3",width=5,height=3,
                   fg="white",bg="blue",
                   command=lambda:self.action(3)).grid(row=3, column=2)
 
            Button(master,text="0",width=5,height=3,
                   fg="white",bg="blue",
                   command=lambda:self.action(0)).grid(row=4, column=0)
 
            Button(master,text=".",width=5,height=3,
                   fg="red",bg="light green",
                   command=lambda:self.action('.')).grid(row=4, column=1)
 
            Button(master,text="(",width=5,height=3,
                   fg="white",bg="blue",
                   command=lambda:self.action('(')).grid(row=2, column=4)
 
            Button(master,text=")",width=5,height=3,
                   fg="blue",bg="orange",
                   command=lambda:self.action(')')).grid(row=2, column=5)
 
            Button(master,text="?",width=5,height=3,
                   fg="red",bg="light green",
                   command=lambda:self.squareroot()).grid(row=3, column=4)
 
            Button(master,text="x²",width=5,height=3,
                   fg="white",bg="blue",
                   command=lambda:self.square()).grid(row=3, column=5)
 
# Driver Code
root = Tk()
 
obj=calc(root) # object instantiated
 
root.mainloop()
 
 

Output: 

 



Next Article
Python Tutorial | Learn Python Programming Language

A

AyanBanerjee3
Improve
Article Tags :
  • Python
  • Python-tkinter
Practice Tags :
  • python

Similar Reads

  • Python Tutorial | Learn Python Programming Language
    Python Tutorial – Python is one of the most popular programming languages. It’s simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
    10 min read
  • Python Interview Questions and Answers
    Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
    15+ min read
  • Python OOPs Concepts
    Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
    11 min read
  • Python Projects - Beginner to Advanced
    Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether you’re a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow. Here’s a list
    10 min read
  • Python Exercise with Practice Questions and Solutions
    Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
    9 min read
  • Python Programs
    Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python c
    11 min read
  • Python Data Types
    Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
    10 min read
  • Enumerate() in Python
    enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list(). Let's look at a simple exa
    3 min read
  • Python Lists
    In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
    6 min read
  • Python Introduction
    Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code. Key Features of PythonPython’s simple and readable syntax makes it beginner-frie
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences