October 10, 2024

How to Create a Simple Calculator in Python using Tkinter GUI – Step by Step

In this tutorial, you will learn how to create a calculator application in Python using Tkinter module.

  1. Plan Your Calculator Layout
  2. Code and Test the Layout (Grid Layout)
  3. Setup the Calculator Screen
  4. Setup the Keypad
  5. Changes the Font sizes
  6. Display Selected Number on Screen
  7. Coding the Assign Key
  8. Coding the Calculate Key
  9. Further Enhancements

Related Tutorial – How to Create a Command Line Calculator in Python

1. Plan Your Calculator Layout

We would adopt a grid layout for the calculator UI. This is shown below. Each of the frames is placed at a given location on the grid. For instance, the display_frame is placed on location (0,0) inside the root_frame. Similarly, the keypad frame is placed at location (1,0) inside the root_frame but in the second row.

I have used the numbers in bold to show the size of the frames. Also,  indentation is used to show the parent-child relationship between the frame.

Calculator Frames Layout
Calculator Frames Layout

 

2. Code and Test the Layout

The code for the frames is quite easy to understand. It follows from the layout discussed above. The little addition is the padding of the frames. We add the attribute padx to specify the left and right padding. The attribute pady specifies the top and bottom padding.

The code for the layout is given below:

import tkinter as tk

window = tk.Tk()
window.title('Simple Python GUI Calculator')

root_frame = tk.Frame(window)
window.geometry('650x600')

display_frame = tk.LabelFrame(root_frame, width=400, height=80)
display_frame.grid(row=0, column=0, pady=(10, 10))
display_frame.grid_propagate(0)

keypad_frame = tk.LabelFrame(root_frame, width=400, height=450)
keypad_frame.grid(row=1, column=0, padx=10, pady=(10, 10))
keypad_frame.grid_propagate(0)

numbers_frame = tk.LabelFrame(keypad_frame, width=260, height=400)
numbers_frame.grid(row=0, column=0, padx=(10, 20), pady=(10, 10))
numbers_frame.grid_propagate(0)

signs_frame = tk.LabelFrame(keypad_frame, width=100, height=400)
signs_frame.grid(row=0, column=1, pady=(10, 10))
signs_frame.grid_propagate(0)

root_frame.pack()

window.mainloop()

 

3. Setup the Calculator Screen

The calculator screen would be a textbox which is Text() in Tkinter. This would positioned at location (0,0) inside the display_frame.

display_box = tk.Text(display_frame, width=20, height=1)
display_box.grid(row=0, column=0, padx=(20, 5), pady=(20, 5))

 

4. Setup the Calculator Keypad

The calculator keypad consists of the numbers_frame and the signs_frame. These are implemented as buttons as shown in the code.

The buttons for the numbers_keypad are placed inside the numbers_frame in 3 by 4 grid. The buttons for the signs_keypad are placed inside the signs_frame 1 by 4 grid.

The code for button 1 and button 2 is given below:

button_1 = tk.Button(numbers_frame, text='1', height=3, width=3)
button_1.grid(row=0, column=0, padx=10, pady=10)

button_2 = tk.Button(numbers_frame, text='2', height=3, width=3)
button_2.grid(row=0, column=1)

You can can complete code for the rest of the buttons or you can get the code from Github here.

Also the button for the addition sign(+) is given below

button_add = tk.Button(signs_frame, text='+', height=3, width=3)
button_add.grid(row=0, column=0, padx=(10, 10), pady=10)

button_subtract = tk.Button(signs_frame, text='-', height=3, width=3)
button_subtract.grid(row=1, column=0)

button_multiply = tk.Button(signs_frame, text='*', height=3, width=3)
button_multiply.grid(row=2, column=0, pady=10)

button_divide = tk.Button(signs_frame, text='/', height=3, width=3)
button_divide.grid(row=3, column=0)

 

5. Change the Font Sizes

Next, the font sizes would have to be increased both for the screen and for the keypad.

For this screen, we want the font size to be 30px. Then it would be single-line display and a font type of ‘Helvetica’. This is achieved using the height and the font attribute of the Text object. The code is given below:

 height=1, font=("Helvetica", 30)

 

Next, to change the font styles for all the buttons, we can use two loop. For each of the two frames: numbers_frame and signs_frame, we would loop through all the buttons inside and apply the same style to each.

The code is given below:

# Apply Styles to the buttons
button_font = font.Font(size=20, weight='bold', family='Helvetica')
for button in numbers_frame.winfo_children():
    button['font'] = button_font

for button in signs_frame.winfo_children():
    button['font'] = button_font

 

6. Display Selected Number on Screen

We need to write a function that executes when a button is clicked. In this case, when a number is clicked, we would take the clicked number and display it on the screen.  The function is given below. It takes a parameter, and inserts the given argument into the display_box(screen). Note that the text is appended to existing text on the display.

def show(num):
    display_box.insert(END, num)

 

Next you will need to add this function to the number button using the command attribute.  So the change to the button would be as shown:

command=lambda num='1': show('1')

 

The Clear Entry (CE) button

You use this button the clear the content of the display. The code for it is shown below:

def clear():
    display_box.delete('1.0', END)

And you also need to add to the command to the CE button as well:

command=lambda: clear()

You can then repeat this for all other numbers. When you are done, run the application an click on each of the number to see that it appears.

 

7. Coding the Assign Key

This are the keys for the operators: add, subtract, multiply and divide. This button is clicked after the user has entered the first number. When this key is clicked, two things happen:

  1. take number on the screen and assign it to a variable (num1)
  2. determine the sign that was clicked and assign it to the variable op (for operator)
  3. clear the display so the the user can enter the second operand

Also note that these variables are global variables. So they be used later when the EQUALS (=) button is clicked. So we first declare them at the beginning of the program as shown here:

global num1
global num2
global op

The calculate function is given below:

def assign(sign):
    global num1
    global op
    op = sign
    num1 = display_box.get('1.0', 'end-1c')
    clear()

 

8. Coding the Calculate Key

The calculate key would perform the calculation and display the result on the screen.

The calculate function performs the following actions:

  1. read the number on the screen into the second variable num2
  2. determine the operation to perform
  3. fetch the first operand from the global variable, num1
  4. perform the operation
  5. display the result on the screen

The calculate function is given below:

def calculate():
    global num2
    global op
    num2 = display_box.get('1.0', 'end-1c')
    result = 0

    # Switch the op to determine which operation to perform
    if op == '+':
        result = float(num1) + float(num2)
    elif op == '-':
        result = float(num1) - float(num2)
    elif op == '*':
        result = float(num1) * float(num2)
    elif op == '/':
        result = float(num1) / float(num2)
    clear()
    display_box.insert(END, result)

 

9. Further Enhancements

  • Erasing figures from displayed values
  • Handling decimal numbers
  • Displaying both the operands and operators on screen with the result
  • Validate inputs

These enhancements and more would be covered in the next part. Then we would move on to Scientific Calculator!

Video Tutorial – How to Build a GUI Calculator in Python

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments