By Dipak Ghosh
Python program to create a Graphical User Interface based Standard Calculator using Tkinter module.
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.
Every tkinter program has the following common steps involved:-
So here we shall create a GUI based standard calculator using the Python Tkinter module, which can perform basic arithmetic operations addition, subtraction, multiplication, and division.
STEP 1 - IMPORT THE TKINTER MODULE
from tkinter import *
STEP 2 - DECLARE GLOBAL VARIABLE
We need a global variable to keep our expression of the calculation so that it is available at all scopes. We shall declare it something like below:-
expression = ""
STEP 3 - WRITING NECESSARY FUNCTIONS
Since we will be creating buttons for the numbers as well as operators we need to declare a few functions for some actions. Like in this case we will have action for pressing. The functions are as follows:-
1. press(num) - This function will be executed when a digit or a decimal point button will be pressed. This function simply updates the expression by concatenatenating the parameter passed num with the global variable expression declared above.
def press(num): # Function to update expression in the text entry box global expression # point out the global expression variable expression = expression + str(num) # concatenation of string equation.set(expression) # update the expression by using set method
2. equalpress() - This function will be executed when equals button will be pressed. Here try and except block is used to handle errors like division by zero , incomplete expression etc. The expression stored in expression variable is then evaluated using inbuilt eval() function of Python and stored in variable total which is then updated and the expression is cleared.
def equalpress(): # Function to evaluate the final expression try: # Put that code inside the try block which may generate the error global expression total = str(eval(expression)) # eval function evaluate the expression and str function convert the result into string equation.set(total) expression = "" # initialze the expression variable by empty string except: # if error is generate then handle by the except block equation.set(" error ") expression = ""
3. clear() - This function will be executed when the clear button will be pressed. This function simply clears the expression and updates it.
def clear(): # Function to clear the contents of text entry box global expression expression = "" equation.set("")
STEP 4 - CREATION OF WINDOW IN main
Now we shall write the driver code. Here we shall write our Driver code where we shall be cresting our containing window and add required buttons and other widgets. Below is the code for creation of window, adding titile of the window and specifing size of the window.
if __name__ == "__main__": tk = Tk() # create a GUI window tk.configure(background="brown") # set the background colour of GUI window tk.title("Standard Calculator") # set the title of GUI window tk.geometry("270x150") # set the size of GUI window
Now we shall add a Text entry where our expression will be added and also create a StringVar() named equation. The Tkinter StringVar helps you manage the value of a widget such as a Label or Entry more effectively.
equation = StringVar() # StringVar() is the variable class we create an instance of this class expression_field = Entry(tk, textvariable=equation) # create the text entry box for showing the expression. expression_field.grid(columnspan=4, ipadx=70) # grid method is used for placing the widgets at respective positions in table like structure.
Now since our expression entry and grid are set we shall keep on adding buttons. The following snippet shoes how it is done.
b1 = Button(tk, text=' 1 ', fg='black', bg='gray',command=lambda: press(1), height=1, width=7) b1.grid(row=2, column=0) b2 = Button(tk, text=' 2 ', fg='black', bg='gray',command=lambda: press(2), height=1, width=7) b2.grid(row=2, column=1) b3 = Button(tk, text=' 3 ', fg='black', bg='gray',command=lambda: press(3), height=1, width=7) b3.grid(row=2, column=2) b4 = Button(tk, text=' 4 ', fg='black', bg='gray',command=lambda: press(4), height=1, width=7) b4.grid(row=3, column=0) b5 = Button(tk, text=' 5 ', fg='black', bg='gray',command=lambda: press(5), height=1, width=7) b5.grid(row=3, column=1) b6 = Button(tk, text=' 6 ', fg='black', bg='gray',command=lambda: press(6), height=1, width=7) b6.grid(row=3, column=2) b7 = Button(tk, text=' 7 ', fg='black', bg='gray',command=lambda: press(7), height=1, width=7) b7.grid(row=4, column=0) b8 = Button(tk, text=' 8 ', fg='black', bg='gray',command=lambda: press(8), height=1, width=7) b8.grid(row=4, column=1) b9 = Button(tk, text=' 9 ', fg='black', bg='gray',command=lambda: press(9), height=1, width=7) b9.grid(row=4, column=2) b0 = Button(tk, text=' 0 ', fg='black', bg='gray',command=lambda: press(0), height=1, width=7) b0.grid(row=5, column=0) p = Button(tk, text=' + ', fg='black', bg='pink',command=lambda: press("+"), height=1, width=7) p.grid(row=2, column=3) m = Button(tk, text=' - ', fg='black', bg='pink',command=lambda: press("-"), height=1, width=7) m.grid(row=3, column=3) mul = Button(tk, text=' * ', fg='black', bg='pink',command=lambda: press("*"), height=1, width=7) mul.grid(row=4, column=3) div = Button(tk, text=' / ', fg='black', bg='pink',command=lambda: press("/"), height=1, width=7) div.grid(row=5, column=3) eq = Button(tk, text=' = ', fg='black', bg='yellow',command=equalpress, height=1, width=7) eq.grid(row=5, column=2) clear = Button(tk, text='Clear', fg='white', bg='black',command=clear, height=1, width=7) clear.grid(row=6, column=3) dec= Button(tk, text='.', fg='black', bg='light blue',command=lambda: press('.'), height=1, width=7) dec.grid(row=5, column=1)
In the above snippet we have added buttons for 1,2,3,4,5,6,7,8,9,0,+,-,*,/,. and have provided them different colors for aome visual appeal. You may change them as per your wish.
Finally we need to start our GUI application. So the mainloop() function is used for the purpose. This function is an infinite loop which is used to run the application, it will wait for an event to occur and process the event as long as the window is not closed.
tk.mainloop()
So when you will run the program you will get an output something like this:-
NOTE - The only drawback this program has is that this program doesn't work when the expression is given through keyboard. You need to use the buttons for entering your expressions.
Submitted by Dipak Ghosh (DGhosh49251)
Download packets of source code on Coders Packet
Comments