Python Advance Workbook OWTP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

Project Workbook

Python (Advance)

www.azureskynet.com | +91-1244275997
1. GUI based login Panel
In this chapter, we will go through the concept of login and signup in a login
panel using GUI (Graphical user interface) and sending the email with
attachment to any mail id. For sending an email using this, first you must have a
mail id on Gmail because here we are going to use the Gmail’s protocol to send
the email. So here is the small app that we are going to create on this chapter.

Icon for your App

This button will take


you to the email page Enter User name
after successful login
Enter Password

This button will ask This button will delete


you to signup for a all the login credentials
successful login stored in a csv file

Importing all the modules to be used


Now, we are going to import all the modules that we are going to use in our
program so that we can get the better understanding of using the module and
also we will understand that why we are using that module in this program. So
let’s start by importing the modules.

from tkinter import * #importing this to create a GUI application

import os #importing this to check that the file is available

that stores the login credentials to verify

import csv #importing this to read the file of csv type


from tkinter import filedialog #importing this to attach the file to
send the email

import smtplib #importing this to allow python to send &


receive emails

#import the rest of the modules to allow the smtp server to send or
receive the attachment with the email

from email.mime.multipart import MIMEMultipart

from email.mime.base import MIMEBase

from email.mime.text import MIMEText

from email import encoders

Storing the credentials


Our next step is to create a new variable and store the path to the login
credentials so that we can further access it and authenticate the user so as to
further send or receive the email with or without the attachments. Also create
two more variables to work as the counters which we are going to use to to
confirm that the attachment has be added or not and also to confirm that the
mail has been sent or not. So, create two more variables and initialize them with
a value 0.

count, c=0,0

creds = '/tempfile.temp' #path of the credentials that stores


the username and password of different authorised users
Creating the GUI Login/signup page
Now, let’s start by creating or login/signup page for our GUI application which
will be displayed to you when your program will run. As you have already gone
through the sessions on GUI so I consider that now you all have a basic
understanding of how to create different widgets using tkinter module in GUI.
So, let’s create the main page as shown below:

In the above main page we used 3 different widgets, i.e., Label, Entry and
Button. In the creating of this page we will first create a window manager in
which we will add the above widgets and further we will add the title to the
window and also add the icon to the window to make your window more
attractive. Now look on the code below to understand the code.

def login(): #creating a login function

#creating the global variables so as to use globally

global nameEL

global pwordEL

global rootA

#creating a window manager

rootA=Tk()
#giving a title to your window

rootA.title('Login')

#setting up the icon for your window

rootA.iconbitmap(r'20170115_144259.ico')

#creating a label widget to set up the heading to your page

intruction=Label(rootA,text='Please Login\n')

intruction.grid(sticky=E) #setting up the position of label

#creating the labels to ask the user to enter the username


and password; also to setting up their positions using the grid

nameL=Label(rootA,text='Username: ')

pwordL=Label(rootA,text='Password: ')

nameL.grid(row=1,sticky=W)

pwordL.grid(row=2,sticky=W)

#creating the entries to let the user enter the username and
password; also to setting up their positions using the grid

nameEL=Entry(rootA)

pwordEL=Entry(rootA,show='*')

nameEL.grid(row=1,column=1)

pwordEL.grid(row=2,column=1)
#creating the buttons to login, signup and delete user, also
setup their properties with the labels on them

loginB=Button(rootA,text='Login',relief=GROOVE,
command=CheckLogin)

loginB.grid(columnspan=2,sticky=W)

loginB=Button(rootA,text='Signup',relief=GROOVE,
command=Signup)

loginB.grid(columnspan=2,sticky=W)

rmuser=Button(rootA,text='Delete User', fg='red',


relief=GROOVE, command=DelUser)

rmuser.grid(column=2,sticky=W)

#to close the window manually

rootA.mainloop()

Now you can see in case of each button widget we have to pass a command and
that command is a function so we have to create functions for login, signup and
delete user as CheckLogin, Signup and DelUser respectively. Now let’s see what
we are gonna do in each function and how it will work when the button will be
pressed. Firstly let’s see what will happen when you will click the login button so
let’s start creating out first function, i.e. , CheckLogin

def CheckLogin(): #creating a function to authenticate user

global ro #creating a global variable

#opening the credentials in a read mode and then checking each


record to verify the authorised user

with open(creds) as f:
data=csv.reader(f) #reading credentials in csv format

for line in data: #checking each line in the credential

try:

#storing the records from each line in variables uname


and pword respectively

uname=line[0]

pword=line[1]

#matching the uname and pword with the username and


password entered by the user respectively

if nameEL.get() == uname and pwordEL.get() == pword:

#destroy the current window & create a new window


to display the message in case of correct credentials

rootA.destroy()

r=Tk()

r.title(':D')

r.iconbitmap(r'20170115_144259.ico')

r.geometry('150x50')

rlbl=Label(r,text='\n[+] Logged In')

rlbl.pack()

r.mainloop()

send()

#calling the send() function to send an email


except IndexError: #in case of IndexError pass
statement is passed to avoid raising the error

pass

else:

#In case the credentials didn’t match

r=Tk()

r.title(':D')

r.iconbitmap(r'20170115_144259.ico')

r.geometry('150x50')

rlbl=Label(r,text='\n[!] Invalid Login')

rlbl.pack()

r.mainloop()

login()

#In case the credentials didn’t match login() function is called

As you can see in the above code, for the case when credentials got matched
window with message “Login successful” is called up and at the end send()
function is called. So our next step is to create the window to set up two
buttons one to compose a new email and other one to logout from your profile
and the window created by the function send() will look like.
Creating your profile window
Now to create you window for send() function let’s create a function using the
tkinter (for GUI).

def send(): #creating a function to create new window to logout


and compose a new email and further sent it with or
without attachment

global ro

ro=Tk()

ro.title('Send Message')

ro.iconbitmap(r'20170115_144259.ico')

ro.geometry('200x100') #setting up the size of the window

new=Button(ro,text='New Message, relief=GROOVE,command=mail)

new.grid(row=1,column=0,sticky=N)

new=Button(ro, text='Log Out', relief=GROOVE, command=logout)

new.grid(row=1,column=2,sticky=N)

ro.mainloop()

Creating window to compose email


Now from the above code it will be very clear to that we have created a new
window consisting of two buttons one to compose message and other to logout
and both the buttons will call a function when they are clicked separately those
are mail and logout respectively. So the next step is to create a mail() and
logout() functions which will open up a new window to compose an email with or
without attachment and we will first create the mail() function.

def mail(): #creating a function with multiple functions to compose an


email

def attach(): #creating a function to attach a file with email

global count #setting up count as global variable

count+=1 #incrementing the counter

#calling the dialog window to ask you to select a file to attach

root.filename = filedialog.askopenfilename(initialdir = "/",title


= "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))

#displaying path of selected file in a label widget in current


window and setting up the position of label

file=Label(root,text=root.filename)

file.grid(row=7,column=0,sticky=W)

def Pass(): #creating a pass() function to do nothing

pass

def Sendmail(): #creating Sendmail() function to send email


with or without attachment

global count

global c

msg=MIMEMultipart() #creating an object to send multiple


stuff
msg['From']='[email protected]' #sender’s mail id

msg['To']= Toe.get() #send to multiple users

msg['Subject']= Subjecte.get() #setup the subject to the


email

body = texte.get("1.0","end-1c") #fetching main message


from the text widget
from the compose window

msg.attach(MIMEText(body,'plain')) #combining the body of


the email with rest of
the message

if count>0: #combining the attachment with rest of the


message so that all the parts of the mail could
be send as one

filename = root.filename

attachment=open(filename,'rb')

part=MIMEBase('application','octet-stream')

part.set_payload((attachment).read())

encoders.encode_base64(part)

part.add_header('Content-Disposition',"attachment;
filename="+filename)

msg.attach(part)

else:

pass

text=msg.as_string() #converting the main message into string


#setup the Gmail protocol to send or receive emails

mail=smtplib.SMTP('smtp.gmail.com',587)

mail.ehlo()

mail.starttls()

mail.login("[email protected]","Abc@123")

try:

mail.sendmail("[email protected]",msg['To'],text)

c+=1 #incrementing the counter c

print('email sent')

except:

print ('error sending email')

mail.quit()

root.destroy()

if c >= 1:

#if mail was sent successfully the new window is opened


and following message is displayed

r=Tk()

r.title(':D')

r.iconbitmap(r'20170115_144259.ico')

r.geometry('150x50')

rlbl=Label(r,text='\n[+] Email sent')

rlbl.pack()

r.mainloop()
else:

r=Tk()

r.title(':D')

r.iconbitmap(r'20170115_144259.ico')

r.geometry('150x50')

rlbl=Label(r,text='\n[!] Error Sending Email')

rlbl.pack()

r.mainloop()

Creating the compose panel


#The code below will display the following window to compose an
email
root=Tk()

root.title('New Message')

root.iconbitmap(r'20170115_144259.ico')

To=Label(root,text="To:")

Subject=Label(root,text="Subject:")

text=Label(root,text="Message:")

To.grid(row=1,column=0,sticky=W)

Subject.grid(row=2,column=0,sticky=W)

text.grid(row=3,column=0,sticky=NW)

Toe=Entry(root,width=67)

Subjecte=Entry(root,width=67)

texte=Text(root,width=50,height=5)

Toe.grid(row=1,column=1,sticky=W)

Subjecte.grid(row=2,column=1,sticky=W)

texte.grid(row=3,column=1,sticky=W)

attach=Button(root,text="Attach",relief=GROOVE,
command=attach)

attach.grid(row=6,column=1,sticky=W)

send=Button(root,text="Send",relief=GROOVE,command=Sendmail)

send.grid(row=6,column=0,sticky=W)

file=Label(root,text='')
file.grid(row=7,column=0,sticky=W)

root.geometry('500x170')

root.mainloop()

Logout of your profile


So this was the all about the mail() function and using this function you will be
able to send your mail to any mail id with or without attachment and with
subject. Now our next step is to create a function to logout using the logout()
function.

def logout(): #creating a function to logout

ro.destroy()

r=Tk()

r.title(':D')

r.iconbitmap(r'20170115_144259.ico')

r.geometry('150x100')

rlbl=Label(r,text='\n[+] Logged Out Successfully.')

rlbl.pack()

r.mainloop()

login()

The following window will be displayed when you will click on the logout
button.
Signing up for new user
Till now we have discussed and understood all about the login function and also
we have discussed about all the functionalities of the further actions that will
takes places in between this process. Now let’s move to our next function which
will be called when you will click on the signup button. So here is how you will
create a function to signup and the following window will be opened after the
button clicked.

def Signup(): #creating a signup function to add new user

global pwordE #creating a global variable

global nameE

global roots

rootA.destroy()

roots=Tk() #this creates the window just a blank one

roots.title("Signup")

roots.iconbitmap(r'20170115_144259.ico')
#this puts a label so just a piece of text saying 'please enter ...'

intruction=Label(roots,text='Please Enter new Credidentials\n')

intruction.grid(row=0,column=0,sticky=E)

nameL=Label(roots,text='New Username: ')

pwordL=Label(roots,text='New Password: ')

nameL.grid(row=1,column=0,sticky=W)

pwordL.grid(row=2,column=0,sticky=W)

nameE=Entry(roots) #this now puts on text box waiting for input

pwordE=Entry(roots,show='*') #same as above ,yet show ='*'

what this does is just replace

he text with the '*' like a

password box :D

nameE.grid(row=1,column=1)

pwordE.grid(row=2,column=1)

signupButton=Button(roots,text='Signup',relief=GROOVE,
command=FSSignup)

signupButton.grid(columnspan=2,sticky=W)

roots.mainloop()

def FSSignup():

with open(creds,'a') as f: #update the user name and password

in the credentials for the new user


f.write(nameE.get()) #fetching the name from the name

text

f.write(',') #seperating username and password with comma

f.write(pwordE.get()) #fetching the password

f.write('\n') #creating a new line after each credentials

f.close() #closes the file

roots.destroy() #this will destroy the signup window

login() #this will move us on to the login window to validate

Deleting the credentials for all users


So this was the way how you can signup new user and updates the credentials
with the new user’s login credentials. Now let’s see how you can delete the
complete database or say the complete records of the users on clicking the
delete button.

def DelUser(): #creating a function to delete credentials

os.remove(creds) #removing the credentials file from the

directory it is stored in

rootA.destroy()

Signup() #taking you to signup page so as to start creating

new credentials
Condition check and Login/Signup
Now when you have done creating all the functions to validate or to create a
user or to delete the credentials. Now the final step is to validate the
credentials and accordingly call its first window when the program runs.

if os.path.isfile(creds): #checking whether credentials are there


on the specified path or not ,if yes then login() window is called

login()

else:

Signup() #else signup window is called


2. Snake Game
In this chapter we will discuss that how you can create your own snake game
in an easy way and you will enjoy creating and playing that too. So we will be
using the interactive command window to display and play snake game. So in
snake game what happens is we control the direction of the snake and take
the snake to the food and the snake eats the food and after eating the food
size of the snake increases and again the snake move to the next hunt as the
position of the food changes automatically every time after the snake eats
it. So here is a picture of the snake game that we are going to create here.

Your score Boundaries for the


snake

Food for the snake

Snake searching for food

Importing the modules Used


Now when you know what actually happens in a snake game. So we can start
creating our snake game using python. For that let’s first see what are the
modules that we are going to use in this game. So the modules used are :

#importing the modules curses and sys

import curses,sys

#importing key functions from the curses module to contol snake


from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN

from random import randint #importing random function

Installation of curses module


In the above modules all the modules are the inbuilt modules except the one,
i.e., curses which we have to install first to use it in our program and this is
the main modules for this program. So let’s see how to install it:

Open command prompt and type the following command and press enter.

C:\> pip install curses

Before running this command please makes sure that you have a working
internet connection on your system.

Initializing screen to Play


So the first step to create any game is to initialize a window/screen on which
we will display all the playing stuff so we can visualize the action on
controlling with the keypad. So to initialize the screen we will use the
following commands.

#initialization of new window/screen to start the game

sys.__stdout__ = sys.stdout

curses.initscr()

win = curses.newwin(20, 60, 0, 0) #setting up the boundaries for


the play zone

Activation of keypad
So when you have initialized a screen and set up the boundaries for your play
zone. Now it’s time to activate the keypad so as to control the direction of
your snake and let the snake eat his food and accordingly change his length.
So for that we will use the win object that we have created during the
creation of the screen.

win.keypad(1) #to activate the keypad to play

curses.noecho()

curses.curs_set(0) #used to hide the cursor from the screen

#set the border properties to make border visible

win.border(0)

win.nodelay(1)

Initialization Parameters
So we have set up all the parameters to create a play zone and to display the
boundaries. Now let’s create new variables and initialize them with a value. So
create four variables first one to set up the initial direction to move your
snake, second one to initialize the value of your score, third one to set the
length and coordinates of your snake and the last one to set the initial
position for the food for your snake. Here we will use the addch method from
the win object to print the food on its coordinate and we’ll specify the
character that will be displayed in place of the food.

key = KEY_RIGHT # Initializing values (Direction)

score = 0

snake = [[4,10], [4,9], [4,8]] # Initial snake co-ordinates

food = [10,20] # First food co-ordinates

win.addch(food[0], food[1], '*') # Prints the food as *


Starting the Game to Play
Now when you have initialized the variables and preset the initial coordinates
for the snake and its food then your next step is to start playing and within
the play zone. For that we are going to start a loop with a condition of Esc
key not pressed, so that you could manually interrupt the game and also we
are going to repeat these steps again and again to move the snake all around
and to achieve a high score by eating the snake’s food. So set a condition for
while loop as,

while key != 27: # While Esc key is not pressed

win.border(0)

#this will print the score and the sting SNAKE on the top

win.addstr(0, 2, 'Score : ' + str(score) + ' ')

win.addstr(0, 27, ' SNAKE ')

# Increases the speed of Snake as its length increases

win.timeout(int(150 - (len(snake)/5 + len(snake)/10)%120))

prevKey = key # In case of no change previous key is used

event = win.getch()

key = key if event == -1 else event

#If SPACE BAR is pressed it will pause/resume the game

if key == ord(' '):

key = -1

while key != ord(' '):

key = win.getch()
key = prevKey

continue

# If any other key is pressed other than the specified ones


then previous key action will take place

if key not in [KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN,


27]:

key = prevKey

# Calculates the new coordinates of the head of the snake to


increase the length of snake when snake eats the food

snake.insert(0, [snake[0][0] + (key == KEY_DOWN and 1) +


(key == KEY_UP and -1), snake[0][1] + (key == KEY_LEFT and -1)
+ (key == KEY_RIGHT and 1)])

# If snake crosses the boundaries, make it enter from the


other side on both x-axis and y-axis

if snake[0][0] == 0: snake[0][0] = 18

if snake[0][1] == 0: snake[0][1] = 58

if snake[0][0] == 19: snake[0][0] = 1

if snake[0][1] == 59: snake[0][1] = 1

# Exit if snake crosses the boundaries (use this when you want
to limit the play zone)

#if snake[0][0] == 0 or snake[0][0] == 19 or snake[0][1] == 0


or snake[0][1] == 59: break
# If snake hits itself

if snake[0] in snake[1:]: break

if snake[0] == food: # When snake eats the food

food = []

score += 1

# Using the random function to change the coordinates of


food and move to the next position

while food == []:

food = [randint(1, 18), randint(1, 58)] #food=(y,x)

if food in snake: food = []

win.addch(food[0], food[1], '*') #set the food coordinates

and food character to show

else:

last = snake.pop() # If it does not eat the food,

length decreases

win.addch(last[0], last[1], ' ')

#set the snake coordinates and snake character to show

win.addch(snake[0][0], snake[0][1], '#')


Finishing and closing the Window
So we have created the game to play in the play zone where you can have a
better experience of playing and creating the game. Now when you have added
different conditions to exit the loop, now our next step is to display the final
score on the screen when your game ends because when the loop will exit it will
not display anything instead the window will also gets exited so we have to
display the score on the window and also to hold that window until we wants to
exit it. So add the following lines to give a proper exit and also to display your
final score.

#exits the curses window that we created

curses.endwin()

#Display the Final score on the screen on exit

print("\nGame Over\nYour Score - " + str(score))

#hold the screen until you press enter

input('')

So this was the way how you can create your own snake game and also you have
got the good hands on experience of working with the curses module. Similarly,
you can use curses in different way to create your own game to play and share
with your friends. I hope you all will do well and will create a more advance
games like this.

You might also like