You are on page 1of 111

Python Tkinter (GUI)

&
VUI
Programs
mhmeducations.com
Tutorial 1

mhmeducations.com
Simple Program
from tkinter import *
root = Tk()
mainloop()

mhmeducations.com
Window of 400*400 Pixel
from tkinter import *
root = Tk()
root.geometry("400x400")
mainloop()

mhmeducations.com
Window with Title
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")
mainloop()

mhmeducations.com
Window with Message(Label)
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")
my_label=Label(root, text='IT Skill Training')
my_label.pack()
mainloop()
mhmeducations.com
Window with Message
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")
my_label=Label(root, text='IT Skill Training')
my_label.pack()
my_label=Label(root, text='mhmeducations.com')
my_label.pack()
mainloop()

mhmeducations.com
Front ground (fg) and Back ground(bg)
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")
my_label=Label(root, text='IT Skill Training', fg='blue')
my_label.pack()
my_label=Label(root, text='mhmeducations.com', bg='white')
my_label.pack()
mainloop()

mhmeducations.com
Tutorial 2

mhmeducations.com
Width and Height and space
between two sentence (pady)
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")
my_label=Label(root, text='IT Skill Training', fg='blue',bg='white', width=50)
my_label.pack()
my_label=Label(root, text='mhmeducations.com', bg='white',height=10)
my_label.pack(pady=50)
mainloop()

#pady=50 mean 50 pixel down


mhmeducations.com
Font and size
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")
my_label=Label(root, text='IT Skill Training', fg='blue',bg='white',
width=50)
my_label.pack()
my_label=Label(root, text='mhmeducations.com', font=('Helvtica',30))
my_label.pack(pady=50)
mainloop()

mhmeducations.com
Check changing it
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")
my_label=Label(root, text='IT Skill Training', relief='sunken')
my_label.pack()
my_label=Label(root, text='mhmeducations.com', font=('Helvtica',30))
my_label.pack(pady=50)
mainloop()

mhmeducations.com
Check changing it
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")
my_label=Label(root, text='IT Skill Training', relief='raised')
my_label.pack()
my_label=Label(root, text='mhmeducations.com', font=('Helvtica',30))
my_label.pack(pady=50)
mainloop()

mhmeducations.com
Check changing it
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")
my_label=Label(root, text='IT Skill Training', relief='groove')
my_label.pack()
my_label=Label(root, text='mhmeducations.com', font=('Helvtica',30))
my_label.pack(pady=50)
mainloop()

mhmeducations.com
Tutorial 3

mhmeducations.com
grid
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")
my_label=Label(root, text='IT Skill Training', bg="white", width=50)
my_label.grid(row=0,column=0)
my_label=Label(root, text='mhmeducations.com')
my_label.grid(row=0,column=1)
mainloop() mhmeducations.com
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")
my_label=Label(root, text='IT Skill Training',
bg="white", width=50)
my_label.grid(row=0,column=0)
my_label=Label(root, text='mhmeducations.com')
my_label.grid(row=1,column=0)
mainloop()
mhmeducations.com
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")
my_label=Label(root, text='IT Skill Training',
bg="white", width=50)
my_label.grid(row=0,column=0)
my_label=Label(root, text='mhmeducations.com')
my_label.grid(row=1,column=0, sticky=W)
mainloop()
mhmeducations.com
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")
my_label=Label(root, text='IT Skill Training',
bg="white", width=50)
my_label.grid(row=0,column=0)
my_label=Label(root, text='mhmeducations.com')
my_label.grid(row=1,column=0, sticky=E)
mainloop()
mhmeducations.com
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")
my_label=Label(root, text='IT Skill Training',
bg="white", width=50)
my_label.grid(row=0,column=0)
my_label=Label(root, text='mhmeducations.com')
my_label.grid(row=1,column=1)
my_label=Label(root, text='MHM is best')
my_label.grid(row=2,column=2)
mainloop() mhmeducations.com
Tutorial 4

mhmeducations.com
Button

mhmeducations.com
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")

# Create clicked function

def clicked():
my_label2 = Label(root, text="mhmeducations.com")
my_label2.pack()

# Create Buttons
my_button = Button(root, text="Click Me!", command=clicked)
my_button.pack(pady=20)

mainloop() mhmeducations.com
Entry Widget

mhmeducations.com
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")
def clicked(): # Create clicked function
input = e.get()
my_label2 = Label(root, text="Hello " + input)
my_label2.pack()
my_label = Label(root, text='Enter Your Name:') # Create labels
my_label.pack()
#Create Entry Widget Input Box
e = Entry(root, font=("Helvetica", 18))
e.pack(pady=20)
my_button = Button(root, text="Click Me!", command=clicked) # Create Buttons
my_button.pack(pady=20)
mainloop()
Add Image

mhmeducations.com
from tkinter import *
from PIL import ImageTk, Image (# install pillow)

root = Tk()
root.title("Hello World!")
root.geometry("400x900")

# Add Images
my_image = ImageTk.PhotoImage(Image.open("logo.png"))
image_label = Label(image=my_image)
image_label.pack()
mhmeducations.com
Show and Hide button

mhmeducations.com
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")

def clicked():
global my_label2
my_label2 = Label(root, text="mhmeducations.com")
my_label2.pack()

def hide():
my_label2.pack_forget()

def show():
my_label2.pack()

my_button = Button(root, text="Click Me!", command=clicked)


my_button.pack(pady=20)

hide_button = Button(root, text="Hide", command=hide)


hide_button.pack(pady=20)

show_button = Button(root, text="Show", command=show)


show_button.pack(pady=20)
Toolbar

mhmeducations.com
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")

def fake_command():
pass

my_menu = Menu(root)
root.config(menu=my_menu)

file_menu = Menu(my_menu)
my_menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="New", command=fake_command)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit)

root.mainloop()
Tutorial 5

mhmeducations.com
Status bar
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")

my_status = Label(root, text="Waiting", bd=2, relief="sunken", anchor=W, width=400)


my_status.grid(row=2, column=0, sticky=S)

root.mainloop()

mhmeducations.com
Radio button
Program in two slide

mhmeducations.com
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")

def radio():
if v.get() == "one":
my_label = Label(root, text="You Clicked Radio Button One!")
else:
my_label = Label(root, text="You Clicked Radio Button Two!")
my_label.pack(pady=10)
v = StringVar()

rbutton_1 = Radiobutton(root, text="One", variable=v,


value="one").pack()
rbutton_2 = Radiobutton(root, text="Two", variable=v,
value="two").pack()

my_button = Button(root, text="Click Me", command=radio)


my_button.pack(pady=20)

root.mainloop()

mhmeducations.com
Check box

mhmeducations.com
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")

v = StringVar()

my_check = Checkbutton(root, text="MHM", variable=v)


my_check.deselect()
my_check.pack()

root.mainloop()

mhmeducations.com
Tutorial 6

mhmeducations.com
Pop up

mhmeducations.com
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("MHM")
root.geometry("400x400")

def popup():
response = messagebox.showinfo("mhm", "mhmeducations.com")
my_label = Label(root, text=response).pack(pady=10)

pop_button = Button(root, text="Click To Pop Up!", command=popup)


pop_button.pack(pady=20)

root.mainloop()
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("MHM")
root.geometry("400x400")

def popup():
response = messagebox. askyesno("mhm", "mhmeducations.com")
my_label = Label(root, text=response).pack(pady=10)

pop_button = Button(root, text="Click To Pop Up!", command=popup)


pop_button.pack(pady=20)

root.mainloop()
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("MHM")
root.geometry("400x400")

def popup():
response = messagebox. askokcancel("mhm", "mhmeducations.com")
my_label = Label(root, text=response).pack(pady=10)

pop_button = Button(root, text="Click To Pop Up!", command=popup)


pop_button.pack(pady=20)

root.mainloop()
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("MHM")
root.geometry("400x400")

def popup():
response = messagebox. askquestion("mhm", "mhmeducations.com")
my_label = Label(root, text=response).pack(pady=10)

pop_button = Button(root, text="Click To Pop Up!", command=popup)


pop_button.pack(pady=20)

root.mainloop()
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("MHM")
root.geometry("400x400")

def popup():
response = messagebox. showerror("mhm", "mhmeducations.com")
my_label = Label(root, text=response).pack(pady=10)

pop_button = Button(root, text="Click To Pop Up!", command=popup)


pop_button.pack(pady=20)

root.mainloop()
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("MHM")
root.geometry("400x400")

def popup():
response = messagebox. showwarning("mhm", "mhmeducations.com")
my_label = Label(root, text=response).pack(pady=10)

pop_button = Button(root, text="Click To Pop Up!", command=popup)


pop_button.pack(pady=20)

root.mainloop()
Tutorial 7

mhmeducations.com
Combo Box

mhmeducations.com
from tkinter import *
from tkinter import ttk
root = Tk()
root.geometry("400x400")

def select():
if my_combo.get() == "Monday":
my_label = Label(root, text="Monday!").pack(pady=10)
if my_combo.get() == "Tuesday":
my_label = Label(root, text="Tuesday!").pack(pady=10)

options = ["Monday","Tuesday"]

my_combo = ttk.Combobox(root, value=options)


my_combo.current(0)
my_combo.pack(pady=10)

my_button = Button(root, text="Select", command=select).pack()


root.mainloop()
New Window

mhmeducations.com
from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.geometry("400x400")

def open_window():
new = Toplevel()
new.title("Second Window")
new.geometry("500x700")
my_label = Label(new, text="second window!").pack(pady=20)
destroy_button = Button(new, text="Quit", command=new.destroy)
destroy_button.pack(pady=5)
kill_original = Button(new, text="Quit Original", command=root.destroy).pack()
new.mainloop()

my_button = Button(root, text="Open 2nd Window", command=open_window).pack()


root.mainloop()
Choose a color

mhmeducations.com
from tkinter import *
from tkinter import colorchooser

root = Tk()
root.title("Hello World!")
root.geometry("400x400")

def color():
my_color = colorchooser.askcolor()[1]
my_label = Label(root, text=my_color).pack()
my_label2 = Label(root, text="You Picked A Color!!",
bg=my_color).pack()

my_button = Button(root, text="Pick A Color", command=color).pack()

root.mainloop() mhmeducations.com
Panel

mhmeducations.com
pane1 = PanedWindow(bd=4, relief="raised", bg="red")
pane1.pack(fill=BOTH, expand=1)

left = Label(pane1, text="left pane")


pane1.add(left)

pane2 = PanedWindow(pane1, orient=VERTICAL, bd=4, relief="raised", bg="blue")


pane1.add(pane2)

top = Label(pane2, text="top pane")


pane2.add(top)

bottom = Label(pane2, text="bottom pane")


pane2.add(bottom)

mainloop()
Tutorial 8

mhmeducations.com
Canvas widget used to draw simple
shapes to complicated graphs

mhmeducations.com
#The Canvas widget used to draw simple shapes to complicated graphs

from tkinter import *

root = Tk()

C = Canvas(root, bg ="purple", height = 350, width = 350)

line = C.create_line(250, 150, 350, 250, fill ="red")

arc = C.create_arc(200, 180, 100,230, start = 0, extent = 250, fill ="blue")

oval = C.create_oval(100, 50, 160, 170, fill ="yellow")

C.pack()
root.mainloop()

mhmeducations.com
Menu widget

mhmeducations.com
from tkinter import *
from tkinter.ttk import *

root = Tk() # creat tkinter window


root.title('Menu Demonstration')

menubar = Menu(root) # Creat Menubar

file = Menu(menubar) # Adding Menu


menubar.add_cascade(label ='File', menu = file)
file.add_command(label ='New', command = None)
file.add_separator()
file.add_command(label ='Exit', command = root.destroy)

help_ = Menu(menubar) # Adding Menu


menubar.add_cascade(label ='Help', menu = help_)
help_.add_command(label ='Demo', command = None)
help_.add_separator()
help_.add_command(label ='About Tk', command = None)

root.config(menu = menubar) # display Menu


mainloop() mhmeducations.com
Spinbox Widgets

mhmeducations.com
from tkinter import *

root = Tk()
root.geometry("300x300")

w = Label(root, text ='mhm', font = "100")


w.pack()

sp = Spinbox(root, from_= 0, to = 50)


sp.pack()

root.mainloop()
mhmeducations.com
Progessbar

mhmeducations.com
from tkinter import * progress['value'] = 90
from tkinter.ttk import *
root = Tk() root.update_idletasks()
time.sleep(2)
# Progress bar widget
progress = Progressbar(root, orient = progress['value'] = 100
HORIZONTAL, length = 100)
root.update_idletasks()
# Function for progress bar value time.sleep(2)
def probar():
import time
progress['value'] = 10 progress.pack()
root.update_idletasks()
time.sleep(2)
# the progress bar
progress['value'] = 50 Button(root, text = 'Click here', command =
root.update_idletasks() probar).pack()
time.sleep(2)
mainloop()
mhmeducations.com
Toplevel Widget

mhmeducations.com
from tkinter import *

root = Tk()
root.geometry("300x400")

root.title("main")

l1 = Label(root, text = "This is main window")

top = Toplevel()
top.geometry("200x200")
top.title("TOP LEVEL")
l2 = Label(top, text = "This is TOPLEVEL window")

l1.pack()
l2.pack()

top.mainloop() mhmeducations.com
Tutorial 9

mhmeducations.com
File Frame
• Program in two slide

mhmeducations.com
from tkinter import *
root = Tk()
root.title("MHM")
root.geometry("400x400")
def fake_command():
pass
def new():
hide_menu_frames()
file_frame.grid(row=1, column=0, columnspan=2, padx=20, pady=20)
def fake_command():
pass
def new():
file_frame.grid(row=1, column=0, columnspan=2, padx=20, pady=20)
my_menu = Menu(root)
root.config(menu=my_menu)
#Create Menu Items
file_menu = Menu(my_menu)
my_menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="New", command=new)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit)

# File Menu Frame


file_frame = Frame(root, width=400, height=400, bd=5, bg="blue", relief="sunken")
file_frame_label = Label(file_frame, text="File Frame", font=("Helvetica", 20))
file_frame_label.pack(padx=20, pady=20)

root.mainloop()
Entry Widgets with Grid
Program in two slide

mhmeducations.com
from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.geometry("400x400")

hello_label = Label(root)

#Submit Function
def submit():
global hello_label
clear()
hello_label = Label(root, text="Hello " + e.get())
hello_label.grid(row=3, column=0)
mhmeducations.com
#Create clear function
def clear():
hello_label.grid_forget()

# Forget
my_label = Label(root, text="Enter Your Name:").grid(row=0, column=0)

e = Entry(root)
e.grid(row=1, column=0)

my_button = Button(root, text="Submit", command=submit).grid(row=2, column=0)

clear_button = Button(root, text="Clear", command=clear).grid(row=2, column=1)

root.mainloop()

mhmeducations.com
Tutorial 10

mhmeducations.com
destroy() method

mhmeducations.com
from tkinter import *
from tkinter.ttk import *
root = Tk()

b1 = Button(root, text ="Button 1", command = root.destroy)


# window will be destroyed
b1.pack(pady = 50)

b2 = Button(root, text ="Button 2", command = b1.destroy)


# button 1 will be destroyed
b2.pack(pady = 50)

mainloop() mhmeducations.com
askopenfile() function

mhmeducations.com
from tkinter import *
from tkinter.ttk import *
from tkinter.filedialog import askopenfile
root = Tk()
root.geometry('300x300')

def open_file():
file = askopenfile(mode ='r', filetypes =[('Python Files', '*.py')])
if file is not None:
content = file.read()
print(content)

b1 = Button(root, text ='Open', command = lambda:open_file())


b1.pack(side = TOP, pady = 50)

mainloop()
mhmeducations.com
bind function:- it is universal widget
method

mhmeducations.com
from tkinter import *
from tkinter.ttk import *
root = Tk()
root.geometry('300x300')

def enter(event):
print('Curser is on Window')

def exit_(event):
print('Curser is not on window')

frame = Frame(root, height = 250, width = 250)

frame.bind('<Enter>', enter) #working of bind function


frame.bind('<Leave>', exit_)
frame.pack()

mainloop() mhmeducations.com
Tutorial 11

mhmeducations.com
asksaveasfile() function

mhmeducations.com
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import asksaveasfile

root = Tk()
root.geometry('300x300')

def save():
files = [('All Files', '*.*'), # open and ask to save file
('Python Files', '*.py'),
('Text Doc', '*.txt'),
('Image file', '*.jpg')]
file = asksaveasfile(filetypes = files, defaultextension = files)

b1 = ttk.Button(root, text = 'Save', command = lambda : save())


b1.pack(side = TOP, pady = 20)

mainloop() mhmeducations.com
MessageBox Widget

mhmeducations.com
from tkinter import *
from tkinter import messagebox

root = Tk()
root.geometry("300x200")

messagebox.askquestion("Are you sure?")

messagebox.askokcancel("Want to continue?")

messagebox.askyesno("are you born in July?")

messagebox.askretrycancel("Do you want to Try again?")

messagebox.showinfo("Information about installation")

messagebox.showwarning("Don't Ingore Warning")

messagebox.showerror("Error is generator")

root.mainloop()
mhmeducations.com
Hierarchical treeview in GUI application

mhmeducations.com
from tkinter import *
from tkinter import ttk
root = Tk()
root.geometry("400x400")

root.title("GUI Application wirh TreeView")

ttk.Label(root, text ="Hierarchical Treeview").pack()

treeview = ttk.Treeview(root) # Create treeview window


treeview.pack()

treeview.insert('', '0', 'item1', text ='Main Heading') # Inserting parent or root of tree

treeview.insert('', '1', 'item2', text ='Sub Heading1') # Inserting child or branches


treeview.insert('', '2', 'item3', text ='Sub Heading2')

treeview.insert('item2', 'end', text ='Product 1') #inserting Leaf or items


treeview.insert('item2', 'end', text ='Product 2')
treeview.insert('item3', 'end', text ='Product 1')

treeview.move('item2', 'item1', 'end') # Join Parents and child


treeview.move('item3', 'item1', 'end')
mhmeducations.com
root.mainloop()
Scale Widget:- Horizontal Scale

mhmeducations.com
from tkinter import *
root = Tk()
root.geometry("300x300")
v1 = DoubleVar()

def readscale():
sel = "Horizontal Scale Value = " + str(v1.get())
l1.config(text = sel)

s1 = Scale( root, variable = v1,from_ = 1, to = 1000, orient = HORIZONTAL)


l3 = Label(root, text = "Scale")
b1 = Button(root, text ="Display the Reading",command = readscale, bg = "orange")
l1 = Label(root)

s1.pack()
l3.pack()
b1.pack()
l1.pack()

root.mainloop() mhmeducations.com
Scale Widget:- Vertical Scale

mhmeducations.com
from tkinter import *
root = Tk()
root.geometry("300x300")
v1 = DoubleVar()

def readscale():
sel = "Horizontal Scale Value = " + str(v1.get())
l1.config(text = sel)

s1 = Scale( root, variable = v1,from_ = 1, to = 1000, orient = VERTICAL)


l3 = Label(root, text = "Scale")
b1 = Button(root, text ="Display the Reading",command = readscale, bg = "orange")
l1 = Label(root)

s1.pack()
l3.pack()
b1.pack()
l1.pack()

root.mainloop() mhmeducations.com
Tutorial 12

mhmeducations.com
focus_set() and focus_get() method

mhmeducations.com
from tkinter import *
from tkinter.ttk import *
root = Tk()

def focus(event): #Name the Widgets which is Focus


widget = root.focus_get()
print(widget, "has focus")

e1 = Entry(root)
e1.pack(expand = 1, fill = BOTH)

e2 = Button(root, text ="Button on Focus")


e2.pack(pady = 10)
e2.focus_set() #Make Button on Focus

e3 = Radiobutton(root, text ="MHM")


e3.pack(pady = 10)

root.bind_all("<Button-1>", lambda e: focus(e))


mainloop()
mhmeducations.com
forget_pack() method

mhmeducations.com
from tkinter import *
from tkinter.ttk import *
root = Tk()

def forget(widget):
widget.forget()

def retrieve(widget):
widget.pack(fill = BOTH, expand = True)

b1 = Button(root, text = "Forget Label", command = lambda : forget(my_label))


b1.pack(fill = BOTH, expand = True)

b2 = Button(root, text = "Retrive Label", command = lambda : retrieve(my_label))


b2.pack(fill = BOTH, expand = True)

my_label=Label(root, text='mhmeducations.com')
my_label.pack(fill = BOTH, expand = True)

mainloop()
mhmeducations.com
forget_grid() method

mhmeducations.com
from tkinter import *
from tkinter.ttk import *
root = Tk()

def forget(widget):
widget.grid_forget()

def retrieve(widget):
widget.grid(row = 0, column = 0)

my_label=Label(root, text='mhmeducations.com')
my_label.grid(row = 0, column = 0)

b1 = Button(root, text = "Forget Label", command = lambda : forget(my_label))


b1.grid(row = 0, column = 1)

b2 = Button(root, text = "Retrive Label", command = lambda : retrieve(my_label))


b2.grid(row = 0, column = 2)

mainloop()
mhmeducations.com
after method in Tkinter
• Destroying Window

mhmeducations.com
from tkinter import *
from tkinter.ttk import *
from time import time
root = Tk()

button = Button(root, text = 'Destroy')


button.pack()

print('Its Running Now............')

start = time()

root.after(10000, root.destroy) #10000 miliseconds means 10 Second

mainloop()

end = time()
print('Destroyed after % d seconds' % (end-start)) mhmeducations.com
after method in Tkinter
• Prompting Window

mhmeducations.com
from tkinter import *
from tkinter.ttk import *
from time import time
from tkinter.messagebox import _show

root = Tk()

button = Button(root, text = 'New Window')


button.pack()

print('Its Running Now............')

start = time()

root.after(10000, lambda : _show('Title', 'Prompting after 10 seconds'))

mainloop()

end = time()
mhmeducations.com
Speech to Text

mhmeducations.com
#Install following
• pip install speechrecognition
• pip install wheel
• pip install pyttsx3
• pip install pipwin
• pipwin install pyaudio

mhmeducations.com
import speech_recognition as sr
import pyttsx3

r = sr.Recognizer() # recognizer initialization

def SpeakText(command): # convert text to speech

engine = pyttsx3.init() #engine initialization


engine.say(command)
engine.runAndWait()

mhmeducations.com
# Write infinite loop for user to speak

while True:
try:

with sr.Microphone() as source2: # use the microphone as source for input


r.adjust_for_ambient_noise(source2, duration=0.2) #listens to user's input
audio2 = r.listen(source2) # Using google to recognize audio
MyText = r.recognize_google(audio2)
MyText = MyText.lower()
print(“You Might Said "+MyText)
SpeakText(MyText)
except sr.RequestError as e:
print("Could not request results; {0}".format(e))
except sr.UnknownValueError:
print(“Speak Again")

mhmeducations.com
Text to Speech

mhmeducations.com
#Install following
• pip install pyttsx3

mhmeducations.com
#text to speech
#Install following
#pip install pyttsx3

import pyttsx3

converter = pyttsx3.init() # Initialize the converter

converter.setProperty('rate', 200) # Sets speed percent


converter.setProperty('volume', 1) # Set volume 0-1

# entered text There will be a pause between each one like a pause in a sentence
converter.say("Hello how are you")
converter.say("I am Piyush Dave")

converter.runAndWait() # Program will not continue until all speech is done talking

mhmeducations.com
Speech Recognition in Python
using Google Speech API

mhmeducations.com
import speech_recognition as sr

AUDIO_FILE = ("Record Example.wav") # use the audio file as the audio source

r = sr.Recognizer()

with sr.AudioFile(AUDIO_FILE) as source:


audio = r.record(source)

try:
print("The Text from audio file are: " + r.recognize_google(audio))

except sr.UnknownValueError:
print("Audio is not Clear")

except sr.RequestError as e:
print("Try Again; {0}".format(e))
mhmeducations.com

You might also like