Python Simple Calculator GUI In Under 40 Lines Of Code
A quick introduction to practical GUI Programming
We are using Tkinter, a standard GUI library that comes with python. Therefore, no pip installs are needed if you already have python.
I am using vim as my editor but you can use any editor you like. Vim is my choice. we will have the same results.
Begin by importing all contents of the Tkinter library with this command.
from tkinter import *
2. We then want to create an instance of the Tkinter frame. This will help us display the root of our window and manage all the components of our calculator application.
We shall also make a title for our application that will show up on the title bar. We, therefore, have to write,…
root = Tk()
root.title("Simple Calculator")
3. After that we have to create an entry area (which we are going to call “myInput”) where the characters we input will be displayed for us to see.
After creating it, we shall use another grid function to place it on the grid of our app at a specified row and column position.
myInput = Entry(root, width = 35)
myInput.grid(row =0, column = 0, columnspan =4, padx = 5, pady = 10)
4. We are now going to create a list and another variable initialized to 0 that we shall use to traverse the list. The reason for a list is that we are going to be using a for loop to place all these input buttons on the grid but instead of using 16 to 32 lines of code, we shall only be using about 6 lines of code to do the same thing.
Let's create the list first and in the list, we shall put characters in the order that we want them to appear on the grid. I am going to call the list “bValues” and the variable, “i”
bValues = [‘7’,’8',’9',’C’,’4',’5',’6',’+’,’1',’2',’3',’-’,’0',’/’,’*’,’=’]
i = 0
5. We are now going to create a for loop. However, it is important to understand that this loop must come after another function that will add functionality to our buttons. I am only writing it before the functionality part so that you can understand the logic behind what we are doing without getting confused.
The for loop is composed of 2 loops where one is nested. The first loop goes through the rows of the grid while the next loop goes through the columns.
During each loop, the idea is to create a button, label that button with the ith element in the list (values), and also have a command that passes the list element over to the function that will be adding functionality to our calculator. This also means that we shall need to increment our “ i ” variable by one in each loop.
We shall denote the rows by “r”, the columns by “c” and the buttons by “myButton”.
for r in range(4):
for c in range(4):
myButton = (root, text = bValues[i], relief = "groove", padx = 20, pady = 10, command = lambda x= bValues[i]: button_do(x))
myButton.grid(row = r+1, column = c)
i+=1
“button_do” is the function that should come before the for loop. This is what will add functionality to each of the buttons that are on the calculator.
The next function is the “button_do” function which should come before the for loop.
6. The “button_do” function has one argument which we assigned to x under the lambda function during our for loop. This argument is nothing but the ith character being passed on to the “button_do” function.
This is important because, when we pass the ith character, we can run if-statements that will track which of the buttons is clicked and this will give us the control we need to add the necessary functionality to the calculator such as inserts and operations.
The idea is to create an if statement with 3 conditions. The first condition is if someone wants to get rid of what's in the entry box. This is the “clear condition. ”
The next condition is if the user wants to type stuff into the calculator. This is the“ entry condition. ”
The last condition is if the user wants to evaluate whatever they just typed and come up with an answer. This is the “evaluation condition”
Lets begin by defining the function and then setting the first condition.
def button_do(j):
if j == "C":
myInput.delete(0, END)
#This function will clear the screen of our calculator.
Under the same “button_do” function block, we shall then consider the second condition which lets users type a bunch of stuff into the calculator. Whatever is typed is captured and displayed on our app’s screen for us to see.
…
elif j != "=":
current = myInput.get() #stores whats on screen somewhere
myInput.delete(0, END) #then deletes what is on the screen
myInput.insert(0, str(current)+ str(j)) #this then inserts the updated entries and are displayed as your inputs.
Last but not least, we have the evaluation condition. This is the “=” button. Once clicked, the idea is to take whatever is currently being displayed, evaluate it and then display the result.
This means that we will first get whatever is currently displayed on our screen and store it in a variable called “expression”. Then we shall delete the displayed stuff. We shall then evaluate our expression and store the result in a variable called final answer and we shall finally display that value on that result.
I used a separate if-statement with this evaluation condition but I suppose an “elif” statement works just fine.
…
if j == "=":
expression = myInput.get()
myInput.delete(0, END)
finalAnswer = eval(str(expression))
myInput.insert(0, str(finalAnswer))
7. Lastly, we want to make sure that our Tkinter frame keeps looping till we close the program. This is why we close the code with this line.
root.mainloop()
We now have a functioning simple calculator that works really well based on the defined functions.
Your practice should you decide to do it could be to expand on the calculator, add more functionality and so on. Through this, you will learn a lot about working with GUIs.
All the best.
About the Creator
James Ssekamatte
Engineer and artist sharing my perpective with the world.


Comments
There are no comments for this story
Be the first to respond and start the conversation.