The Wayback Machine - https://web.archive.org/web/20240930160905/https://www.geeksforgeeks.org/python-simple-gui-calculator-using-tkinter/
Open In App

Python | Simple GUI calculator using Tkinter

Last Updated : 11 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: Tkinter Introduction, lambda function 

Python offers multiple options for developing a 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 GUI applications. Creating a GUI using Tkinter is an easy task.

To create a Tkinter:

  1. Importing the module – tkinter
  2. Create the main window (container)
  3. Add any number of widgets to the main window
  4. Apply the event Trigger on the widgets.

Below is what the GUI looks like:

Let’s create a GUI-based simple calculator using the Python Tkinter module, which can perform basic arithmetic operations addition, subtraction, multiplication, and division.

Below is the implementation: 

Python3




# Python program to create a simple GUI
# calculator using Tkinter
 
# import everything from tkinter module
from tkinter import *
 
# globally declare the expression variable
expression = ""
 
 
# Function to update expression
# in the text entry box
def press(num):
    # point out the global expression variable
    global expression
 
    # concatenation of string
    expression = expression + str(num)
 
    # update the expression by using set method
    equation.set(expression)
 
 
# Function to evaluate the final expression
def equalpress():
    # Try and except statement is used
    # for handling the errors like zero
    # division error etc.
 
    # Put that code inside the try block
    # which may generate the error
    try:
 
        global expression
 
        # eval function evaluate the expression
        # and str function convert the result
        # into string
        total = str(eval(expression))
 
        equation.set(total)
 
        # initialize the expression variable
        # by empty string
        expression = ""
 
    # if error is generate then handle
    # by the except block
    except:
 
        equation.set(" error ")
        expression = ""
 
 
# Function to clear the contents
# of text entry box
def clear():
    global expression
    expression = ""
    equation.set("")
 
 
# Driver code
if __name__ == "__main__":
    # create a GUI window
    gui = Tk()
 
    # set the background colour of GUI window
    gui.configure(background="light green")
 
    # set the title of GUI window
    gui.title("Simple Calculator")
 
    # set the configuration of GUI window
    gui.geometry("270x150")
 
    # StringVar() is the variable class
    # we create an instance of this class
    equation = StringVar()
 
    # create the text entry box for
    # showing the expression .
    expression_field = Entry(gui, textvariable=equation)
 
    # grid method is used for placing
    # the widgets at respective positions
    # in table like structure .
    expression_field.grid(columnspan=4, ipadx=70)
 
    # create a Buttons and place at a particular
    # location inside the root window .
    # when user press the button, the command or
    # function affiliated to that button is executed .
    button1 = Button(gui, text=' 1 ', fg='black', bg='red',
                    command=lambda: press(1), height=1, width=7)
    button1.grid(row=2, column=0)
 
    button2 = Button(gui, text=' 2 ', fg='black', bg='red',
                    command=lambda: press(2), height=1, width=7)
    button2.grid(row=2, column=1)
 
    button3 = Button(gui, text=' 3 ', fg='black', bg='red',
                    command=lambda: press(3), height=1, width=7)
    button3.grid(row=2, column=2)
 
    button4 = Button(gui, text=' 4 ', fg='black', bg='red',
                    command=lambda: press(4), height=1, width=7)
    button4.grid(row=3, column=0)
 
    button5 = Button(gui, text=' 5 ', fg='black', bg='red',
                    command=lambda: press(5), height=1, width=7)
    button5.grid(row=3, column=1)
 
    button6 = Button(gui, text=' 6 ', fg='black', bg='red',
                    command=lambda: press(6), height=1, width=7)
    button6.grid(row=3, column=2)
 
    button7 = Button(gui, text=' 7 ', fg='black', bg='red',
                    command=lambda: press(7), height=1, width=7)
    button7.grid(row=4, column=0)
 
    button8 = Button(gui, text=' 8 ', fg='black', bg='red',
                    command=lambda: press(8), height=1, width=7)
    button8.grid(row=4, column=1)
 
    button9 = Button(gui, text=' 9 ', fg='black', bg='red',
                    command=lambda: press(9), height=1, width=7)
    button9.grid(row=4, column=2)
 
    button0 = Button(gui, text=' 0 ', fg='black', bg='red',
                    command=lambda: press(0), height=1, width=7)
    button0.grid(row=5, column=0)
 
    plus = Button(gui, text=' + ', fg='black', bg='red',
                command=lambda: press("+"), height=1, width=7)
    plus.grid(row=2, column=3)
 
    minus = Button(gui, text=' - ', fg='black', bg='red',
                command=lambda: press("-"), height=1, width=7)
    minus.grid(row=3, column=3)
 
    multiply = Button(gui, text=' * ', fg='black', bg='red',
                    command=lambda: press("*"), height=1, width=7)
    multiply.grid(row=4, column=3)
 
    divide = Button(gui, text=' / ', fg='black', bg='red',
                    command=lambda: press("/"), height=1, width=7)
    divide.grid(row=5, column=3)
 
    equal = Button(gui, text=' = ', fg='black', bg='red',
                command=equalpress, height=1, width=7)
    equal.grid(row=5, column=2)
 
    clear = Button(gui, text='Clear', fg='black', bg='red',
                command=clear, height=1, width=7)
    clear.grid(row=5, column='1')
 
    Decimal= Button(gui, text='.', fg='black', bg='red',
                    command=lambda: press('.'), height=1, width=7)
    Decimal.grid(row=6, column=0)
    # start the GUI
    gui.mainloop()


Output : 

Code Explanation: 

  1. The code starts by importing the necessary modules.
  2. The tkinter module provides all the basic functionality for creating graphical user interfaces.
  3. Next, we create a global variable called expression which will store the result of the calculation.
  4. We also create two functions to update and evaluate the expression.
  5. Finally, we write driver code to initialize and manage our GUI window.
  6. In order to create a simple calculator, we first need to define an expression variable.
  7. This is done by using the global keyword and assigning it an empty string value ( “” ).
  8. Next, we create two functions to update and evaluate the expression.
  9. The press function updates the contents of the text entry box while equalpress evaluates the final result of the calculation.
  10. We next need to create a table-like structure in which our widgets will be placed.
  11. We do this by using grid method which takes three arguments: columnspan , ipadx , and rowspan .
  12. These parameters specify how many columns wide, how many rows high, and how many columns per row respectively should be used in our table layout.
  13. We set columnspan to 4 , meaning that there will be four columns in our table, iPad width divided by 2 (70), multiplied by 1 for each row in our table (iPad height divided
  14. The code creates a simple calculator using the Tkinter module.
  15. First, the code imports everything from the Tkinter module.
  16. Next, the code creates two global variables: expression and total.
  17. The press() function is used to update the expression variable in the text entry box.
  18. The equalpress() function is used to evaluate the final expression.
  19. Finally, the clear() function is used to clear the contents of the text entry box.
  20. Next, the driver code is created.
  21. In this code, if __name__ == “__main__”: is executed which will create a GUI window and set its background color to light green and its title to Simple Calculator.
  22. Next, the geometry() method is used to set the size of the GUI window (270
  23. The code starts with a few basic objects: a Button object, which has properties for text, font, background color, and command; and a grid object.
  24. The first three buttons (button1 through button3) each have their own individual commands associated with them.
  25. When the user clicks on one of these buttons, the corresponding command is executed.
  26. For example, when the user clicks on button1, its command is to press the number 1 key.
  27. Similarly, when the user clicks on button2’s command, it will be to press the number 2 key; and so on.
  28. Similarly, when the user clicks on button4’s command (to increase the value by 1), its grid row and column values will be set to 3 and 0 respectively.
  29. And finally when clicking on button5’s command (to decrease the value by 1), its grid row and column values will be set to 2 and 1 respectively.
  30. The code creates seven buttons, each with its own function.
  31. When the user presses one of the buttons, the corresponding command is executed.
  32. The first button, button1, has the function press(1).
  33. When clicked, this button will execute the code lambda: press(1).
  34. The second button, button2, has the function press(2), and so on.
  35. When all seven buttons have been clicked, their functions will be executed in order.


Previous Article
Next Article

Similar Reads

Python | Distance-time GUI calculator using Tkinter
Prerequisites : Introduction to Tkinter | Using google distance matrix API Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is 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 wa
7 min read
Python - Dynamic GUI Calculator using Tkinter module
Python provides many options for developing GUI like Kivy, PyQT, WxPython, and several others. Tkinter is the one that is shipped inbuilt with python which makes it the most commonly used out of all. Tkinter is easy, fast, and powerful. Beginners can easily learn to create a simple calculator using this article: Python | Simple GUI calculator using
3 min read
Scientific GUI Calculator using Tkinter in Python
Prerequisite: Python GUI – tkinter In this article, we are going to create GUI Scientific Calculator using Python. As you can see, calculating large numbers nowadays is difficult or time-consuming. We've created a simple Scientific Calculator GUI using Python that allows you to perform simple and complex calculations. To implement GUI we will use t
13 min read
Python - Compound Interest GUI Calculator using Tkinter
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the Python GUI Libraries, Tkinter is the most commonly used method. In this article, we will learn how to create a Compound Interest GUI Calculator application using Tkinter. Let’s create a GUI-based Compound Interest Calculator application. Importing the mod
6 min read
Rank Based Percentile Gui Calculator using Tkinter
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. In this article, we will learn how to create a Rank Based - Percentile Gui Calculator application using Tkinter, with a step-by-step guide. Prerequisites: Introduction to TkinterProgram to calculate t
7 min read
Ratio Calculator GUI using Tkinter
Prerequisite: Python GUI – tkinter Tkinter is the most commonly used library for developing GUI (Graphical User Interface) in Python. It is a standard Python interface to the Tk GUI toolkit shipped with Python. As Tk and Tkinter are available on most of the Unix platforms as well as on the Windows system, developing GUI applications with Tkinter be
3 min read
Python | Simple calculator using Tkinter
Prerequisite : Tkinter IntroductionPython 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. Cr
3 min read
Python | Create a GUI Marksheet using Tkinter
Create a python GUI mark sheet. Where credits of each subject are given, enter the grades obtained in each subject and click on Submit. The credits per subject, the total credits as well as the SGPA are displayed after being calculated automatically. Use Tkinter to create the GUI interface. Refer the below articles to get the idea about basics of t
8 min read
Python: Weight Conversion GUI using Tkinter
Prerequisites: Python GUI – tkinterPython offers multiple options for developing a 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 GUI applications. Crea
2 min read
Python | ToDo GUI Application using Tkinter
Prerequisites : Introduction to tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. In this article, we will learn how to create a ToDo GUI application using Tkinter, with a step-by-step guide. To create a tkinter : Importing the module – tkinter
5 min read
Python | GUI Calendar using Tkinter
Prerequisites: Introduction to Tkinter Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to create a GUI Calendar application using
4 min read
Sentiment Detector GUI using Tkinter - Python
Prerequisites : Introduction to tkinter | Sentiment Analysis using Vader Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to creat
4 min read
Python - Morse Code Translator GUI using Tkinter
Prerequisites : Introduction to tkinter | Morse Code Translator Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to create a Morse
6 min read
Python - SpongeBob Mocking Text Generator GUI using Tkinter
Prerequisites : Introduction to tkinter | SpongeBob Mocking Text Generator Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to cre
4 min read
Python - Spell Corrector GUI using Tkinter
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to create a GUI Spell Corrector application using Tkinter, with a step-by-step gu
5 min read
Python - UwU text convertor GUI using Tkinter
Prerequisites :Introduction to tkinter | UwU text convertor Python offers multiple options for developing a 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 crea
4 min read
GST Rate Finder GUI using Python-Tkinter
Prerequisites : Introduction to tkinter | Program to calculate GSTPython offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. In this article, we will learn how to create GST Rate Finder GUI application using Tkinter, with a step-by-step guide. To create a Tki
3 min read
Create Copy-Move GUI using Tkinter in Python
Everyone reading this post is well aware of the importance of Copying the file or moving the file from one specific location to another. In this post, we have tried to explain not only the program but added some exciting pieces of Interface. Up to now, many of you may get about what we are talking about. Yes, you are right, We are going to use "Tki
4 min read
Python - English (Latin) to Hindi (Devanagiri) text convertor GUI using Tkinter
Prerequisites : Introduction to tkinter | Text transliteration from English to Indian languages – Using indic-transliterationPython offers multiple options for developing a 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
4 min read
Standard GUI Unit Converter using Tkinter in Python
Prerequisites: Introduction to tkinter, Introduction to webbrowser In this article, we will learn how to create a standard converter using tkinter. Now we are going to create an introduction window that displays loading bar, welcome text, and user's social media profile links so that when he/she shares his code with some others, they can contact th
12 min read
GUI chat application using Tkinter in Python
Chatbots are computer program that allows user to interact using input methods. The Application of chatbots is to interact with customers in big enterprises or companies and resolve their queries. Chatbots are mainly built for answering standard FAQs. The benefit of this type of system is that customer is no longer required to follow the same tradi
7 min read
Text to speech GUI convertor using Tkinter in Python
Prerequisite: Introduction to Tkinter Tkinter is the standard GUI library for Python. Python when combined with tkinter provides a fast and easy way to create GUI applications.By this library we can make a compelling choice for building GUI applications in Python, especially for applications where a modern sheen is unnecessary, and the top priority
3 min read
Tic Tac Toe game with GUI using tkinter in Python
Tic-tac-toe (American English), noughts and crosses (British English), or Xs and Os is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner. tkinter Python library is used to create the GUI.
15+ min read
Build GUI Application for Guess Indian State using Tkinter Python
In this article, you will learn to make a GUI game in Python, in which we will be shown a map of Indian states and an input prompt were in the prompt, the user has to enter a state name of India. If the user guessed it correctly, the name would hover over its location on the map. You can also see the score as the title of the input prompt window. M
8 min read
Create First GUI Application using Python-Tkinter
We are now stepping into making applications with graphical elements, we will learn how to make cool apps and focus more on its GUI(Graphical User Interface) using Tkinter. What is Tkinter?Tkinter is a Python Package for creating GUI applications. Python has a lot of GUI frameworks, but Tkinter is the only framework that’s built into the Python sta
12 min read
Create a GUI to check Domain Availability using Tkinter
There might be a case where a user wants to create a website and having certain ideas for the website's name but is struck on their availability. So let's develop a GUI that will check for domain availability. We will use the Python-whois module to get information about the website. It's able to extract data for all the popular TLDs (com, org, net,
2 min read
Create a GUI to Get Domain Information Using Tkinter
Prerequisites: Python GUI – tkinter Domain information is very important for every user. It contains information like Name, organization, State, city, Ip address, emails, server name, etc. In this article, we will write code for getting domain information and bind it with GUI Application. We will use the Python-whois module to get information about
2 min read
Python GUI - PyQt VS TKinter
A GUI toolkit contains widgets that are used to create a graphical interface. Python includes a wide range of Interface implementations available, from TkInter (it comes with Python, ) to a variety of various cross-platform solutions, such as PyQt5, which is known for its more sophisticated widgets and sleek look. PyQt PyQt is a toolkit for graphic
4 min read
How to add PDF in Tkinter GUI Python ?
In this article, We are going to see how to add a PDF file Tkinter GUI, For that, we don't have a direct widget to do this. For that, We need to have python version 2.7 or more. And you need to install the 'tkPDFViewer' library. This library allows you to embed the PDF file in your Tkinter GUI. Installation: To install this library you just have to
2 min read
How to embed Matplotlib charts in Tkinter GUI?
Prerequisite: Introduction to Tkinter | Introduction to Matplotlib When Matplotlib is used from Python shell, the plots are displayed in a default window. The plots can be embedded in many graphical user interfaces like wxpython, pygtk, or Tkinter. These various options available as a target for the output plot are referred to as 'backends'. There
3 min read
Article Tags :
Practice Tags :