Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to build a simple GUI calculator using tkinter in Python
Building a GUI calculator with tkinter is an excellent way to practice Python GUI development. This tutorial will guide you through creating a functional calculator with custom icons and a clean interface.
Setup and Requirements
First, install the required image processing library ?
pip install Pillow
For this project, you'll need calculator button icons. Create a folder structure like this ?
+---Working Directory
+---calculator.py
+---assets
+---Calculator
+---Logo.ico
+---one.PNG
+---two.PNG
+---(other button icons)
Required Imports
from tkinter import * from PIL import Image, ImageTk
Global Variables and Functions
Initialize the global variables to track calculator state ?
txt = ""
res = False
ans = 0
def press(num):
global txt, ans, res
if res == True:
txt = str(ans)
res = False
txt = txt + str(num)
equation.set(txt)
def equal():
try:
global txt, ans, res
ans = eval(txt)
equation.set(str(ans))
res = True
except:
equation.set("ERROR: Invalid Equation")
txt = ""
def clear():
global txt, ans, res
txt = ""
equation.set("")
res = False
Creating the Main Window
if __name__ == "__main__":
window = Tk()
window.configure(background="black")
window.title("Calculator")
window.geometry("343x417")
window.resizable(0, 0)
# Display field
equation = StringVar()
txt_field = Entry(relief=RIDGE, textvariable=equation, bd=10,
font=("Arial", 20), bg="powder blue")
txt_field.grid(columnspan=4, ipady=10, ipadx=10, sticky="nsew")
Adding Calculator Buttons
Here's how to create image-based buttons. This example shows the number 1 button ?
width = 80
height = 80
# Number 1 button
img1 = Image.open("assets/Calculator/one.PNG")
img1 = img1.resize((width, height))
oneImage = ImageTk.PhotoImage(img1)
button1 = Button(window, image=oneImage, bg="white",
command=lambda: press(1), height=height, width=width)
button1.grid(row=2, column=0, sticky="nsew")
Complete Calculator Code
from tkinter import *
from PIL import Image, ImageTk
txt = ""
res = False
ans = 0
def press(num):
global txt, ans, res
if res == True:
txt = str(ans)
res = False
txt = txt + str(num)
equation.set(txt)
def equal():
try:
global txt, ans, res
ans = eval(txt)
equation.set(str(ans))
res = True
except:
equation.set("ERROR: Invalid Equation")
txt = ""
def clear():
global txt, ans, res
txt = ""
equation.set("")
res = False
if __name__ == "__main__":
window = Tk()
window.configure(background="black")
window.title("Calculator")
window.geometry("343x417")
window.resizable(0, 0)
equation = StringVar()
txt_field = Entry(relief=RIDGE, textvariable=equation, bd=10,
font=("Arial", 20), bg="powder blue")
txt_field.grid(columnspan=4, ipady=10, ipadx=10, sticky="nsew")
width = 80
height = 80
# Number buttons (1-9, 0)
for i in range(1, 10):
img = Image.open(f"assets/Calculator/{['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'][i-1]}.PNG")
img = img.resize((width, height))
photo = ImageTk.PhotoImage(img)
button = Button(window, image=photo, bg="white",
command=lambda x=i: press(x), height=height, width=width)
button.image = photo # Keep a reference
row = 2 + (i-1) // 3
col = (i-1) % 3
button.grid(row=row, column=col, sticky="nsew")
# Zero button
img0 = Image.open("assets/Calculator/zero.PNG")
img0 = img0.resize((width, height))
zeroImage = ImageTk.PhotoImage(img0)
button0 = Button(window, image=zeroImage, bg="white",
command=lambda: press(0), height=height, width=width)
button0.grid(row=5, column=1, sticky="nsew")
# Operation buttons
operations = [
("multiply.PNG", "*", 2, 3),
("add.PNG", "+", 3, 3),
("subtract.PNG", "-", 4, 3),
("divide.PNG", "/", 5, 3)
]
for filename, symbol, row, col in operations:
img = Image.open(f"assets/Calculator/{filename}")
img = img.resize((width, height))
photo = ImageTk.PhotoImage(img)
button = Button(window, image=photo, bg="white",
command=lambda s=symbol: press(s), height=height, width=width)
button.image = photo
button.grid(row=row, column=col, sticky="nsew")
# Equal button
imgeq = Image.open("assets/Calculator/equal.PNG")
imgeq = imgeq.resize((width, height))
eqImage = ImageTk.PhotoImage(imgeq)
buttoneq = Button(window, image=eqImage, bg="white",
command=equal, height=height, width=width)
buttoneq.grid(row=5, column=2, sticky="nsew")
# Clear button
imgclear = Image.open("assets/Calculator/clear.PNG")
imgclear = imgclear.resize((width, height))
clearImage = ImageTk.PhotoImage(imgclear)
buttonclear = Button(window, image=clearImage, bg="white",
command=clear, height=height, width=width)
buttonclear.grid(row=5, column=0, sticky="nsew")
window.mainloop()
Key Features
| Feature | Implementation |
|---|---|
| Display Field | Entry widget with StringVar |
| Button Layout | Grid geometry manager |
| Image Buttons | PIL/Pillow for image processing |
| Error Handling | Try-except for invalid equations |
Conclusion
This calculator demonstrates essential tkinter concepts including widgets, event handling, and grid layout. The use of custom images creates a professional appearance while the global state management ensures proper calculator functionality.
---