Introduction
The most important way to deal with any difficult situation is to keep calm and move on. Not only that, a peaceful mind is extremely important for a healthy and refreshed body. In this case, regular meditation along with exercise gives good results.
Sorry, I'm not a professional meditation expert or fitness advisor but a Programming Lover. Since I have to sit and code most of the day, I created a meditation application using my favorite programming language, Python, to keep my mind calm.
In this tutorial, I will share with you the complete information also with the source code of this project. I hope along with me you too can use this beautiful meditation application. It will reduce your stress while working for a long time before a computer screen, but how exactly, right?
This application has a beautiful feature of a combination of inhaling and exhaling time(5 sec. for each). You can set the time for how long you want to continue the cycle. I hope you probably know the benefits of deep breathing. Despite that, if I take the top most 3 points, it would be,
- Lowering the heart rate
- Regulate the BP(blood pressure)
- To keep our minds relax
There are also many other benefits but they are not our topic today. So let's not waste any more time and get to the point.
👉Visit Also: Language Translator App with Python Tkinter - Google Translate
Features of this Meditation Application
Looking at the user interface of this project you won't believe that it is built using only the Tkinter library. It looks amazing but is just as easy to use. Check out the images below to know it better.
Home Page of the Meditation App |
Main Page of the Meditation App |
Let's talk about the features.
- The default meditation time is set to 60 seconds or 1 minute.
- You can set the time according to your requirement by the "Set Time" button.
- The app performs a 5 second countdown for each 'inhale' and 'exhale' until the set time reaches zero(0).
- The program plays a status message in the background. For example, 'Relax' - during the initial period(first 4 seconds), 'Inhale' - during inhalation, 'Exhale' - during exhalation.
- You can stop meditating by pressing the Home button.
The Project Details
The entire project is based on two Python files ('app.py', and 'settings.py'), and two folders ('Images', and 'Voices'). See the image below to know the project hierarchy better.
Contents of the Project File |
Let me introduce the program files and folders present in the root project directory.
'app.py' - This is the main program file. It handles all the tasks related to managing the graphical interface, including the countdown operation for controlling the inhale and exhale cycles.
'settings.py' - This file contains all the settings used in the meditation application. For example, all image paths, font types, colors, default values of some variables, etc.
'Images' - All images used in the application are stored here.
'Voices' - Remember, a while back, I told you, the program plays a status message of 'Relax', 'Inhale', and 'Exhale'. There are three .mp3 files for each message and they are in this folder.
Requirements
Before you start writing your code just take a break here. Install these necessary libraries if you didn't already.
Use pip3 instead of pip for Linux.
☛Install Pillow: pip install Pillow
☛Install Tkinter: pip install tk
☛Install playsound: pip install playsound
Do watch the entire video to know how this beautiful Meditation App works.
Source Code
I highly recommend you, download the main project folder from my GitHub page via the Download Button below. It will be in .zip format. After that, unzip that file. You will find there two folders('Images', and 'Voices') and inside each folder, corresponding required images and .mp3 files.
Now create two Python files there named 'app.py' and 'settings.py'. Collect the source code from below and run the 'app.py' program.
app.py
Here the help of multi-threading and multiprocessing has taken for time management and background voice playing respectively. To know it better, visit a similar type of project: Countdown Timer in Python.
I have divided the entire code into different functions and commented on each important place. Hope you will understand the program easily once you see it.
'''A Meditation Application in Python - Tkinter Project
- developed by Subhankar Rakshit.
~ PySeek
'''
import time
import settings as st
from tkinter import *
from threading import *
import multiprocessing as mp
from PIL import ImageTk, Image
from playsound import playsound
from tkinter import ttk, messagebox
class Meditation:
def __init__(self, root):
# Window Settings
self.window = root
self.window.geometry(f"{st.width}x{st.height}")
self.window.title('Meditation App')
self.window.resizable(width = False, height = False)
self.window.configure(bg=st.color2)
# Tkinter Frame
self.frame = Frame(self.window, bg=st.color1, \
width=800, height=450)
self.frame.place(x=0, y=0)
# Default values
self.inhale = True
self.exhale = False
self.onHomePage = False
self.defaultTime = st.baseTime
# Calling Home Page
self.HomePage()
# Manage the Home/Welcoming Window
def HomePage(self):
self.Reset()
self.ClearScreen()
self.BgImage(st.bgImage1)
self.StartButton()
self.TimeButton()
self.RemainingTime(self.defaultTime)
# Function to reset the default values
def Reset(self):
self.onHomePage = True
self.inhale = True
self.exhale = False
self.defaultTime = st.baseTime
# Clear all widgets from the Tkinter Frame
def ClearScreen(self):
for widget in self.frame.winfo_children():
widget.destroy()
# Displays the background image
def BgImage(self, img):
image = Image.open(img)
resizedImg = image.resize((st.width, st.height))
self.img1 = ImageTk.PhotoImage(resizedImg)
label = Label(self.frame, image=self.img1)
label.pack()
# Button to Start Meditation
def StartButton(self):
image = Image.open(st.startBtn)
resizedImg = image.resize((130,130))
self.img2 = ImageTk.PhotoImage(resizedImg)
self.button = Button(self.frame, image=self.img2, \
bg=st.color2, border=0, cursor='hand2', \
command=self.MeditationPage)
self.button.place(x=320, y=120)
# Button for setting the duration of mediation
def TimeButton(self):
image = Image.open(st.setTimeBtn)
resizedImg = image.resize((130,40))
self.img3 = ImageTk.PhotoImage(resizedImg)
self.button = Button(self.frame, image=self.img3, \
bg=st.color2, border=0, cursor='hand2', \
command=self.SecondWindow)
self.button.place(x=320, y=270)
# Label to show the remaining time of mediation
def RemainingTime(self, rTime):
mins, secs = divmod(rTime, 60)
self.timeLabel = Label(self.frame, text=f"{mins}:{secs}", \
bg=st.color2, fg=st.color3 ,font=(st.font3, 15))
self.timeLabel.place(x=727, y=25)
# A different window for setting the mediation period
def SecondWindow(self):
self.newWindow = Tk()
self.newWindow.title("Set Time")
self.newWindow.geometry(st.resolution)
self.totalTime = IntVar()
self.chosenTime = ttk.Combobox(self.newWindow, \
textvariable=self.totalTime, values=st.timeList, \
font=(st.font3, 20), width=8)
self.chosenTime.set(1)
self.chosenTime.place(x=160, y=110)
setTimeBtn = Button(self.newWindow, text="Set Time", \
font=(st.font4, 11), bg=st.color5, fg=st.color2, \
cursor='hand2', command=self.GetTime)
setTimeBtn.place(x=185, y=150)
# It takes the time chosen by the user, and calculates in minutes
# and seconds, and displays on the time label.
def GetTime(self):
self.defaultTime = int(self.chosenTime.get()) * 60
self.newWindow.destroy()
mins, secs = divmod(self.defaultTime, 60)
self.timeLabel.config(text=f"{mins}:{secs}")
self.timeLabel.update()
# It manages the Mediation/Second page and all its widgets
def MeditationPage(self):
self.onHomePage = False
self.ClearScreen()
self.BgImage(st.bgImage2)
self.breathLabel = Label(self.frame, text="", \
bg=st.color3, fg=st.color2 ,font=(st.font1, 28))
self.breathLabel.place(x=387, y=172)
self.statusLabel = Label(self.frame, text="", \
bg=st.color2, fg=st.color3 ,font=(st.font4, 20))
self.statusLabel.place(x=360, y=325)
self.RemainingTime(self.defaultTime)
# Call the function for Multi-Threading
self.MultiThreading()
# Function to create a different thread to handle
# time management tasks.
def MultiThreading(self):
self.x = Thread(target=self.CountDown, daemon=True)
self.x.start()
# Creates a Tkinter Button to return to the Home/Welcoming Page
def HomeButton(self):
image = Image.open(st.homeBtn)
resizedImg = image.resize((60, 22))
self.img4 = ImageTk.PhotoImage(resizedImg)
self.button = Button(self.frame, image=self.img4, \
bg=st.color3, border=0, cursor='hand2', command=self.HomePage)
self.button.place(x=20, y=20)
# Function to handle time management tasks
def CountDown(self):
try:
self.UpdateStatus("Relax!")
process = self.PlayVoice(st.Relax)
time.sleep(4)
process.terminate()
self.HomeButton()
while self.defaultTime > 0:
# Inhale CountDown
if self.inhale:
# A separate process to play 'Inhale' voice
process = self.PlayVoice(st.Inhale)
# Countdown inhale time
self.CountInhale()
# Terminate the process
process.terminate()
# Exhale CountDown
elif self.exhale:
# A separate process to play 'Exhale' voice
process = self.PlayVoice(st.Exhale)
# Countdown exhale time
self.CountExhale()
# Terminate the process
process.terminate()
# Time is up
if self.defaultTime <= 0:
self.UpdateStatus("Done!!")
self.UpdateTime(0, 0)
# To Break the outer loop:
# If the user presses the Home button
# during meditation.
if self.onHomePage:
break
# Catch and display any exceptions, if arises.
except Exception as es:
messagebox.showerror("Error!", f"Error due to {es}")
# Function to Count Inhale time repeatedly
# until the time ends up.
def CountInhale(self):
self.inhale = False
self.exhale = True
# getting the default inhale time
inhale = st.inhaleTime
# Update the Status with 'Inhale' text
self.UpdateStatus("Inhale")
while inhale > 0:
# To Break the inner loop: If the user presses
# the Home button during inhaling.
if self.onHomePage:
break
else:
# Update the remaining time of meditation
mins, secs = divmod(self.defaultTime, 60)
self.UpdateTime(mins, secs)
# Update the remaining inhale time
self.UpdateBreathTime(inhale)
# Decrease time by 1 per second
inhale -= 1
self.defaultTime -= 1
time.sleep(1)
# Function to Count Exhale time repeatedly
# until the time ends up.
def CountExhale(self):
self.exhale = False
self.inhale = True
# getting the default exhale time
exhale = st.exhaleTime
# Update the Status with 'Exhale' text
self.UpdateStatus("Exhale")
while exhale > 0:
# To Break the inner loop: If the user presses
# the Home button during exhaling.
if self.onHomePage:
break
else:
# Update the remaining time of meditation
mins, secs = divmod(self.defaultTime, 60)
self.UpdateTime(mins, secs)
# Update the remaining exhale time
self.UpdateBreathTime(exhale)
# Decrease time by 1 per second
exhale -= 1
self.defaultTime -= 1
time.sleep(1)
# Function to update the status: Inhale/Exhale
def UpdateStatus(self, msg):
self.statusLabel.config(text=msg)
self.statusLabel.update()
# Function to update the remaining time
def UpdateTime(self, mins, secs):
self.timeLabel.config(text=f"{mins}:{secs}")
self.timeLabel.update()
def UpdateBreathTime(self, breath):
self.breathLabel.config(text=f"{breath}")
self.breathLabel.update()
# It plays a .mp3 file to express the current
# status of meditation: 'Inhale' or 'Exhale'.
def PlayVoice(self, voice):
process = mp.Process(target=playsound, args=(voice,))
process.start()
return process
# The main function
if __name__ == "__main__":
# Instance of Tk class
root = Tk()
# Object of Meditation class
obj = Meditation(root)
root.mainloop()
settings.py
Not much to say here. You will see nothing but some variables here that are used in the main program. For example, all image paths, font types, colors, default values of some variables, etc. are declared here.
'''Variables used in 'app.py' are present here.
'''
# Screen Size
width = 800
height = 450
# Secondary screen size
resolution = "480x320"
# Background Images
bgImage1 = "Images/BgImage_1.png"
bgImage2 = "Images/BgImage_2.png"
# Button images
startBtn = "Images/StartBtn.png"
setTimeBtn = "Images/SetTimeBtn.png"
homeBtn = "Images/HomeBtn.png"
# List of Time in minutes. You can modify it.
timeList = [1, 3, 5, 7, 10]
# Default inhale and exhale time in seconds.
# Try to keep it as it is. Inhale+Exhale = must be 10.
inhaleTime = 5
exhaleTime = 5
# Default meditation time in seconds
baseTime = 60
# Font choices
font1 = "Times new roman"
font2 = "Helvetica"
font3 = "Courier"
font4 = "Kokila"
# Color choices
color1 = "#63afdb"
color2 = "white"
color3 = "black"
color4 = "yellow"
color5 = "green"
color6 = "sky blue"
# Voice Cover
Relax = "Voices/Relax.mp3"
Inhale = "Voices/Inhale.mp3"
Exhale = "Voices/Exhale.mp3"
Download the necessary stuff
The download button links to the project file available on my GitHub page which allows you to download the file directly from there.
Did you follow all the steps perfectly? If yes, you can enjoy the app now.
Summary
In this tutorial, we discussed a Meditation App developed using the Python language. It has an amazing user interface that has been managed by the Tkinter library. It offers the following features to the user.
- Users can set the time duration they want to meditate
- It repeats 5 seconds of inhalation and 5 seconds of exhalation, one after the other, over and over, until the set time reaches zero(0).
- For added convenience, it plays a voice-over ('inhale' or 'exhale') to inform users of their current breathing status.
The application is too simple to use. You can use it anytime, anywhere. Especially when you are working for long hours in front of your computer screen and have no way to go outside, this beautiful application can reduce your anxiety or stress by improving your breathing cycle in a short duration. This was my main objective for creating this python project.
Do use this application and share your opinion below. If you have any difficulty using it, let me know in the comment section with your problem. I will guide you.
To get more lovely Tkinter Examples, visit the separate page created only for Python Projects. Some examples are given below.
👉Image to Pencil Sketch Converter in Python - Tkinter Project
👉Image to Cartoon Converter in Python - Tkinter Project
👉An Advanced Alarm Clock using Python Tkinter
👉Test Your Typing Speed with Python - Tkinter Project
Have a nice day ahead, cheers!
PySeek