Saturday, December 28, 2024
Google search engine
HomeLanguagesPython | Simple GUI calculator using Tkinter

Python | Simple GUI calculator using Tkinter

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.
RELATED ARTICLES

Most Popular

Recent Comments