Python | Simple GUI calculator using Tkinter
Last Updated :
11 Dec, 2022
Improve
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:
- Importing the module – tkinter
- Create the main window (container)
- Add any number of widgets to the main window
- 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:
# 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:
- The code starts by importing the necessary modules.
- The tkinter module provides all the basic functionality for creating graphical user interfaces.
- Next, we create a global variable called expression which will store the result of the calculation.
- We also create two functions to update and evaluate the expression.
- Finally, we write driver code to initialize and manage our GUI window.
- In order to create a simple calculator, we first need to define an expression variable.
- This is done by using the global keyword and assigning it an empty string value ( "" ).
- Next, we create two functions to update and evaluate the expression.
- The press function updates the contents of the text entry box while equalpress evaluates the final result of the calculation.
- We next need to create a table-like structure in which our widgets will be placed.
- We do this by using grid method which takes three arguments: columnspan , ipadx , and rowspan .
- 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.
- 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
- The code creates a simple calculator using the Tkinter module.
- First, the code imports everything from the Tkinter module.
- Next, the code creates two global variables: expression and total.
- The press() function is used to update the expression variable in the text entry box.
- The equalpress() function is used to evaluate the final expression.
- Finally, the clear() function is used to clear the contents of the text entry box.
- Next, the driver code is created.
- 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.
- Next, the geometry() method is used to set the size of the GUI window (270
- 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.
- The first three buttons (button1 through button3) each have their own individual commands associated with them.
- When the user clicks on one of these buttons, the corresponding command is executed.
- For example, when the user clicks on button1, its command is to press the number 1 key.
- Similarly, when the user clicks on button2's command, it will be to press the number 2 key; and so on.
- 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.
- 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.
- The code creates seven buttons, each with its own function.
- When the user presses one of the buttons, the corresponding command is executed.
- The first button, button1, has the function press(1).
- When clicked, this button will execute the code lambda: press(1).
- The second button, button2, has the function press(2), and so on.
- When all seven buttons have been clicked, their functions will be executed in order.