• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

Code for GUI Calculator in Python [Explained in Detail]

Aniruddha Chaudhari/78354/23
CodePython

In this tutorial, I am sharing code to create a simple basic calculator to add, subtract, divide and multiply two numbers. GUI calculator in Python takes the two numbers as inputs from the user, perform arithmetic operation and display the result on Graphical User Inteface (GUI).

In an earlier article, I have shared a Python complete basic tutorial for beginner. That article is featured with the simple command line code by which you can add, subtract, divide and multiply two numbers using commands.

command line Python Calculator

This is like command line calculator in Python. But…

How to make GUI Calculator in Python?

The intention of the tutorial is not only to make the Calculator but also to understand the how GUI objects are created in Python.

At the end of this tutorial, I will share the complete code for Python calculator. You can copy-paste and use it.

If your intention is to learn the Python, just don’t copy the code. Follow this article step by step, you can write your own code. Trust me you will learn something amazing.

So let’s start.

For creating GUI, we are using PyQt4.QtGui package. It provides inbuilt functionality to create GUI objects like text area, button, labels…

If you don’t have PyQt4.QtGui package installed on your system, you can download and install with this simple command.

sudo apt-get install python-qt4

Let’s start by considering the requirement to create calculator…

For our code to make the calculator, we need…

  • 2 text fields to take the user inputs
  • 4 buttons to perform four different arithmetic operations like add, subtract, divide and multiply
  • 1 label is to display the result

GUI Calculator in Python output

How to create these GUI objects in Python?

Code for Creating text field for user input

txtArea1 = QLineEdit("", widget)
txtArea2 = QLineEdit("", widget)

Code for Creating Clickable GUI buttons

btnAdd = QPushButton("Add", widget)
btnSub = QPushButton("Subtract", widget)
btnDiv = QPushButton("Divide", widget)
btnMul = QPushButton("Multiply", widget)

Python Code for Plotting GUI objects in Widget

There is one widget, inside which we are displaying all the GUI objects.

To display the objects in the widget, we have to position them using…

  • widget.resize()
  • widget.move()

All the GUI objects will be configured inside the init() function. It is the first function to be called.

Based on the button user clicks on, it will call the respective function.

For example, if the user clicks on the multiplication button, it calls multiplication() function. It reads the value from two text fields and performs the multiplication operation.

Reading User Input Values from Text Field:

The value in input text field is in the text format and you need to convert it into an integer before performing arithmetic operations.

This is a simple line of Python code we are using to convert text to an integer.

num1 = int(txtArea1.text())
num2 = int(txtArea2.text())

Performing Arithmetic Operation Based on User Input:

Perform the arithmetic operation on user input num1 and num2 is pretty easy.

Write a dedicated function for each of the arithmetic operation. These functions return the output to the caller.

Display Python Calculator Result:

Assign the output to the label object using label.setText().

label.setText("Output: "+str(num1 * num2))

That’s it. If you take the other programming languages, it is not so much easy to create GUI, but the Python does it with ease.
Now here it is you are looking for…

Code for GUI Calculator in Python

Simply copy and save it in python file. Run it.

import sys
from PyQt4.QtGui import *
#from PyQt4 import QtGui

app = QApplication(sys.argv)
widget = QWidget()
label = QLabel("", widget)

btnAdd = QPushButton("Add", widget)
btnSub = QPushButton("Subtract", widget)
btnDiv = QPushButton("Divide", widget)
btnMul = QPushButton("Multiply", widget)


#txtArea = QPlainTextEdit("Text To Edit", widget)widget.resize

txtArea1 = QLineEdit("", widget)
txtArea2 = QLineEdit("", widget)

def init():

    widget.resize(300, 300)
    widget.move(300, 300)
    widget.setWindowTitle('Calculator')
    widget.show()

    txtArea1.move(20,10)
    txtArea1.show()
    txtArea2.move(20,60)
    txtArea2.show()

    label.setText("")
    label.move(20,110)
    label.show()

    btnAdd.setToolTip('Addition')
    btnAdd.move(20,160)
    btnAdd.clicked.connect(addition)
    btnAdd.show()

    btnSub.setToolTip('Subtraction')
    btnSub.move(110,160)
    btnSub.clicked.connect(subtraction)
    btnSub.show()

    btnDiv.setToolTip('Division')
    btnDiv.move(20,210)
    btnDiv.clicked.connect(division)
    btnDiv.show()

    btnMul.setToolTip('Multiplication')
    btnMul.move(110,210)
    btnMul.clicked.connect(multiplication)
    btnMul.show()


def addition():
    num1 = int(txtArea1.text())
    num2 = int(txtArea2.text())
    label.setFixedWidth(200)
    label.setText("Addition: "+str(num1 + num2))

def subtraction():
    num1 = int(txtArea1.text())
    num2 = int(txtArea2.text())
    label.setFixedWidth(200)
    label.setText("Subtraction: "+str(num1 - num2))

def multiplication():
    num1 = int(txtArea1.text())
    num2 = int(txtArea2.text())
    label.setFixedWidth(200)
    label.setText("Multiplication: "+str(num1 * num2))

def division():
    num1 = int(txtArea1.text())
    num2 = int(txtArea2.text())
    label.setFixedWidth(200)
    label.setText("Division: "+str(num1 / num2))

if __name__ == "__main__":
     init()

app.exec_()

You can modify the field in the code to understand and enhance the GUI for the calculator.

You can enhance this calculator by various ways…

  • Add numeric button so that you can get the values by clicking on the button instead of manually typing in the text area.
  • Add more arithmetic operation such as log, trigonometric function. Write a separate function for each operation and set one button for each operation.

If you want to be an expert in the Python, do read our Python tutorial which is available FREE for all.

Now, this is all for you. Get your hands dirty with code and show your skill. If you have any question related to GUI Calculator in Python, write in a comment.

Happy Pythoning!

Python Interview Questions eBook

Python
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Godson Rapture
    July 9, 2017 at 6:27 pm

    This is a nice tutorial on GUI and I love how you made it practical.

    • Reply
      Aniruddha Chaudhari
      July 9, 2017 at 6:47 pm

      Thanks, Godson!

  • Reply
    Akhila
    July 9, 2018 at 4:48 pm

    hi Aniruddha, i need a help in using tkinter text filed

    • Reply
      Aniruddha Chaudhari
      July 9, 2018 at 6:21 pm

      Hi Akhila,

      Please tell me, how can I help you?

  • Reply
    Omorose
    May 12, 2019 at 12:55 am

    Sir your tutorial is very explicit. my question is: it is not possible to use the mouse to drag n design those widgets (controls) on the form like what is obtainable in VB 6.0 and VB.net before one start coding in Python?

    Am new in Python pls reply…

    Best Regards.

    • Reply
      Aniruddha Chaudhari
      May 13, 2019 at 8:19 am

      Hi Omorsoe,

      Personally, I have not tried using any tool for GUI. You can check this- https://github.com/alejandroautalan/pygubu. It is an Open source GitHub project.

      There is one more http://page.sourceforge.net/. You can try.

    • Reply
      Bob
      October 18, 2020 at 3:11 pm

      You can simply use the QT designer tool for creating the graphical basement of your program.
      for the next step you should convert your QT file (with name.ui format ) to python file (name.py) & then start writing codes for everything that needs.

  • Reply
    Anil Kumar Reddy Nagrimadugu
    May 15, 2019 at 12:59 pm

    Hi Aniruddha,

    I had gone through the GUI Calculator tutorial Explanation is good

    I tried to install it in Windows 10 in python 3.6.6

    for that, I Installed “pip install PyQt5” module

    then I am getting “NameError: name ‘QWidget’ is not defined” error

    can you please check and give me the solution

    • Reply
      Aniruddha Chaudhari
      May 16, 2019 at 10:40 am

      Hi Anil,

      Looks like you have installed PyQt5. The code in this tutorial is based on PyQt4. Either you can try installing PyQt4 or find suitable matching functions in PyQt5.

  • Reply
    Vishesht Gupta
    June 12, 2019 at 8:29 pm
    import sys
    from PyQt5.QtGui import *
    from PyQt5.QtCore import *
    from PyQt5.QtWidgets import *
    
    # from PyQt4 import QtGui
    app = QApplication(sys.argv)
    widget = QWidget()
    label = QLabel("", widget)
    
    btnAdd = QPushButton("Add", widget)
    btnSub = QPushButton("Subtract", widget)
    btnDiv = QPushButton("Divide", widget)
    btnMul = QPushButton("Multiply", widget)
    
    # txtArea = QPlainTextEdit("Text To Edit", widget)widget.resize
    
    txtArea1 = QLineEdit("", widget)
    txtArea2 = QLineEdit("", widget)
    
    
    def init():
        widget.resize(300, 300)
        widget.move(300, 300)
        widget.setWindowTitle('Calculator')
        widget.show()
    
        txtArea1.move(20, 10)
        txtArea1.show()
        txtArea2.move(20, 60)
        txtArea2.show()
    
        label.setText("")
        label.move(20, 110)
        label.show()
    
        btnAdd.setToolTip('Addition')
        btnAdd.move(20, 160)
        btnAdd.clicked.connect(addition)
        btnAdd.show()
    
        btnSub.setToolTip('Subtraction')
        btnSub.move(110, 160)
        btnSub.clicked.connect(subtraction)
        btnSub.show()
    
        btnDiv.setToolTip('Division')
        btnDiv.move(20, 210)
        btnDiv.clicked.connect(division)
        btnDiv.show()
    
        btnMul.setToolTip('Multiplication')
        btnMul.move(110, 210)
        btnMul.clicked.connect(multiplication)
        btnMul.show()
    
    
    def addition():
        num1 = int(txtArea1.text())
        num2 = int(txtArea2.text())
        label.setFixedWidth(200)
        label.setText("Addition: " + str(num1 + num2))
    
    
    def subtraction():
        num1 = int(txtArea1.text())
        num2 = int(txtArea2.text())
        label.setFixedWidth(200)
        label.setText("Subtraction: " + str(num1 - num2))
    
    
    def multiplication():
        num1 = int(txtArea1.text())
        num2 = int(txtArea2.text())
        label.setFixedWidth(200)
        label.setText("Multiplication: " + str(num1 * num2))
    
    
    def division():
        num1 = int(txtArea1.text())
        num2 = int(txtArea2.text())
        label.setFixedWidth(200)
        label.setText("Division: " + str(num1 / num2))
    
    
    if __name__ == "__main__":
        init()
    
    app.exec_()
    • Reply
      Aniruddha Chaudhari
      June 13, 2019 at 6:26 am

      Thanks, Vishesht for sharing PyQt5 code.

  • Reply
    Rajesh varre
    April 12, 2020 at 9:04 am
    from PyQt5.QtGui import *

    Getting this error.

    ImportError: DLL load failed while importing QtGui: The specified module could not be found.
    

    so imported in this way
    import PyQt5
    Now it is throwing me

    app = QApplication(sys.argv)
    NameError: name 'QApplication' is not defined
    

    Kindly, can you suggest me what to do?
    I have used pip install python-qt5

    • Reply
      Aniruddha Chaudhari
      April 12, 2020 at 3:02 pm

      I think you are using a Windows operating system.
      Looks like python3.dll is missing from your installed Python files. Check if it is there. If it is there and you are using virtual environment, copy python3.dll file from c:\python35 (your installed Python directory) to virtualenv\scripts\python3.dll.

  • Reply
    Lanz Rusler
    April 30, 2020 at 11:52 am

    I have this python code for a GUI calculator but need someone who could tell me how to get lambda out of the program from Tkinter import *

    def iCalc(source, side):
        storeObj = Frame(source, borderwidth=4, bd=4, bg="powder blue")
        storeObj.pack(side=side, expand =YES, fill =BOTH)
        return storeObj
    
    def button(source, side, text, command=None):
        storeObj = Button(source, text=text, command=command)
        storeObj.pack(side=side, expand = YES, fill=BOTH)
        return storeObj
    
    class app(Frame):
        def __init__(self):
            Frame.__init__(self)
            self.option_add('*Font', 'arial 20 bold')
            self.pack(expand = YES, fill =BOTH)
            self.master.title('Calculator')
    
            display = StringVar()
            Entry(self, relief=RIDGE, textvariable=display,
              justify='right'
              , bd=30, bg="powder blue").pack(side=TOP,
                                              expand=YES, fill=BOTH)
    
            for clearButton in (["C"]):
                erase = iCalc(self, TOP)
                for ichar in clearButton:
                    button(erase, LEFT, ichar, lambda
                        storeObj=display, q=ichar: storeObj.set(''))
    
            for numButton in ("789/", "456*", "123-", "0.+"):
             FunctionNum = iCalc(self, TOP)
             for iEquals in numButton:
                button(FunctionNum, LEFT, iEquals, lambda
                    storeObj=display, q=iEquals: storeObj
                       .set(storeObj.get() + q))
    
            EqualButton = iCalc(self, TOP)
            for iEquals in "=":
                if iEquals == '=':
                    btniEquals = button(EqualButton, LEFT, iEquals)
                    btniEquals.bind('', lambda e,s=self,
                        storeObj=display: s.calc(storeObj), '+')
    
    
                else:
                    btniEquals = button(EqualButton, LEFT, iEquals,
                       lambda storeObj=display, s=' %s ' % iEquals: storeObj.set
                       (storeObj.get() + s))
    
        def calc(self, display):
                try:
                    display.set(eval(display.get()))
                except:
                    display.set("ERROR")
    
    
    if __name__=='__main__':
     app().mainloop()
    
    • Reply
      Aniruddha Chaudhari
      May 1, 2020 at 10:58 am

      Hi Lanz,

      You can replace the lambda with a typical function. You read about the lambda function.

      • Reply
        Menon
        May 2, 2020 at 10:18 am

        Can you give me an example of what one of the lambda codes would look if it was a typical function? I am a high school student taking a college class and this assignment was given to me in place of an assignment because my grandpa was in the hospital and all I just can’t seem to understand. Was doing good in the class until they did the stay at home order?

        • Reply
          Aniruddha Chaudhari
          October 11, 2020 at 12:22 pm

          Sorry to hear that. You can check the lambda function here in detail. Kindly let me know if you have any doubt while going through it.

  • Reply
    Lanz Rusler
    May 2, 2020 at 10:20 am

    Can you give me a example of what one of the codes would look like. For some reason it is just not clicking with me

    • Reply
      Aniruddha Chaudhari
      October 11, 2020 at 12:19 pm

      The program mentioned in this tutorial is a workable code. Kindly let me know if you find any specific difficulty.

  • Reply
    Justin Kasse
    October 8, 2020 at 4:37 am

    Please excuse my ignorance but when I enter “sudo apt-get install python-qt4” in python shell, it returns an error. Did you specify how to acquire this package and I missed it?

    • Reply
      Aniruddha Chaudhari
      October 9, 2020 at 10:44 pm

      Hi Justin, can you please mention what error message are you seeing after running the command?

  • Reply
    Daniel
    May 29, 2022 at 1:28 pm

    Hello Aniruddha, how do I install pyQt5 on Windows 10, Any MOP on how it is done, please?

    • Reply
      Aniruddha Chaudhari
      July 9, 2022 at 3:07 pm

      Here, pyQt5 is nothing but the Python library so it should be installed as we install any other Python libraries. Ex. pip install pyqt5.

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard