In this article we want to learn How to Build Calculator in Python TKinter, so first of all let’s talk about TKinter, if you are Python Developer, you know that when it comes to building GUI applications in Python, you have different choices one of them are TKinter, now What is Python TKinter?
What is TKinter?
Tkinter is Python library that helps you create graphical user interfaces (GUIs) for your programs. It provides different components, like buttons, labels and entry fields, that you can use to build windows, menus and other visual elements for your applications. TKinter is already packed with Python, so you don’t need to install that.
Now to Build Calculator in Python TKinter you need to follow these steps
1: First you need to import required libraries
1 2 |
import tkinter as tk import re |
2: After that you need to create a class that extends from tk.Tk
1 2 3 |
class Calculator(tk.Tk): def __init__(self): super().__init__() |
3: Then you need to spcifiy the title and geometry of the window
1 2 |
self.title("Codeloop - Calculator") self.geometry("200x200") |
4: In here we creates an Entry widget, which is essentially a single-line text entry field where users can input text or numbers. also we arranges the Entry widget within its parent widget using the grid geometry manager.
1 2 |
self.result = tk.Entry(self) self.result.grid(row=0, column=0, columnspan=4, padx=10, pady=10, ipadx=10, ipady=10) |
5: These are the button list that we want to create
1 2 3 4 5 6 |
button_list = [ "7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", ".", "0", "C", "/" ] |
6: This code creates a grid of buttons in a Tkinter window.
- For each button in the button_list, it creates a Tkinter Button widget with the specified text, width, height, and a command to execute when clicked.
- The button is placed in the grid layout with the specified row and column indices, along with padding on the x and y axes.
- After placing each button, the column index (col) is incremented. If it exceeds 3 (indicating the fourth column in a zero-based index), it resets to 0 and the row index (row) is incremented to move to the next row.
- Finally, a separate button for “=” is created and placed in the fifth row and fourth column of the grid.
1 2 3 4 5 6 7 8 9 10 11 |
for button in button_list: self.button = tk.Button(self, text=button, width=5, height=2, command=lambda btn=button: self.button_click(btn)) self.button.grid(row=row, column=col, padx=10, pady=10) col += 1 if col > 3: col = 0 row += 1 self.equal = tk.Button(self, text="=", width=5, height=2, command=self.calculate) self.equal.grid(row=5, column=3) |
7: This method is called when any button in the calculator is clicked, and it handles the input accordingly.
- If the clicked button is “C” (clear), it deletes all text from the Entry widget (self.result) where users input numbers and operators.
- Otherwise, it inserts the text of the clicked button at the end of the current content in the Entry widget. For example, if the user clicks the button “7”, the digit “7” will be added to the end of the existing content.
1 2 3 4 5 |
def button_click(self, button): if button == "C": self.result.delete(0, tk.END) else: self.result.insert(tk.END, button) |
8: This method performs the calculation based on the input expression entered in the calculator.
- It retrieves the input expression from the Entry widget (self.result) where users input numbers and operators.
- Using a regular expression(re.sub(r'[^0-9\+\-\*\/\.]’, ”, self.result.get())), it removes any characters from the input expression that are not digits, arithmetic operators (+, -, *, /), or decimal points.
- Then, it attempts to evaluate the sanitized input expression using Python eval() function, which calculates the result of the expression.
- If the calculation succeeds, the result is displayed in the Entry widget.
- If there’s an error during the calculation (such as division by zero or invalid input), it displays “Error” in the Entry widget.
1 2 3 4 5 6 7 8 |
def calculate(self): try: input_str = re.sub(r'[^0-9\+\-\*\/\.]', '', self.result.get()) self.result.delete(0, tk.END) self.result.insert(tk.END, eval(input_str)) except: self.result.delete(0, tk.END) self.result.insert(tk.END, "Error") |
This is the complete code for building calculator with Python TKinter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
import tkinter as tk import re class Calculator(tk.Tk): def __init__(self): # Call the constructor of the superclass (tk.Tk) super().__init__() # Set the title and size of the window self.title("Codeloop - Calculator") self.geometry("200x200") # Create an Entry widget for displaying the result self.result = tk.Entry(self) self.result.grid(row=0, column=0, columnspan=4, padx=10, pady=10, ipadx=10, ipady=10) # List of buttons for the calculator button_list = [ "7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3", "*", ".", "0", "C", "/" ] # Variables to keep track of the current row and column row = 1 col = 0 # Create buttons for each item in the button_list for button in button_list: # Create a Button widget with text and command self.button = tk.Button(self, text=button, width=5, height=2, command=lambda btn=button: self.button_click(btn)) # Place the button in the grid layout self.button.grid(row=row, column=col, padx=10, pady=10) # Move to the next column col += 1 # Reset column and move to the next row if column exceeds 3 if col > 3: col = 0 row += 1 # Create the '=' button for calculation self.equal = tk.Button(self, text="=", width=5, height=2, command=self.calculate) self.equal.grid(row=5, column=3) # Method called when a button is clicked def button_click(self, button): # If 'C' button is clicked, clear the Entry widget if button == "C": self.result.delete(0, tk.END) else: # Otherwise, insert the button's text into the Entry widget self.result.insert(tk.END, button) # Method to calculate the expression in the Entry widget def calculate(self): try: # Get the input expression from the Entry widget input_str = re.sub(r'[^0-9\+\-\*\/\.]', '', self.result.get()) # Clear the Entry widget self.result.delete(0, tk.END) # Calculate the result and display it in the Entry widget self.result.insert(tk.END, eval(input_str)) except: # Handle any errors and display "Error" in the Entry widget self.result.delete(0, tk.END) self.result.insert(tk.END, "Error") # Create an instance of the Calculator class calculator = Calculator() calculator.mainloop() |
Run the complete code and this will be the result
Subscribe and Get Free Video Courses & Articles in your Email