Object Oriented Programming: Numeriano B. Aguado John Ren G. Santos

You might also like

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

Object Oriented Programming

Numeriano B. Aguado
John Ren G. Santos

[Date]
Table of Contents

Module 8: Advanced Python Modules, Objects and Data 181

Introduction 181
Learning Objectives 182
Lesson 1: Collections Module 182
Lesson 2: Math and Random Modules 189
Lesson 3: Unzipping and Zipping Files 194
Lesson 4: Advanced Numbers 196
Lesson 5: Advanced Strings 198
Lesson 6: Advanced Sets 201
Lesson 7: Advanced Dictionaries 206
Lesson 8: Advanced Lists 208
Assessment Task 214
Summary 216
Reference 216

MODULE 9: Working with Images, PDFs in Python 217


Introduction 217
Learning Objectives 217
Lesson 1: Working with Images 218
Lesson 2: Working with PDF Files 229
Assessment Task 233
Summary 235
Reference 235

MODULE 10: GUI: An Introduction 236


Introduction 236
Learning Objectives 236
Lesson 1: Introduction to GUI with Tkinter in Python 237
Lesson 2: Widgets 240
Lesson 3: Geometry Management 241
Lesson 4: Binding or Command Functions 245
Lesson 5: Alert Boxes 247
Lesson 6: Rendering Images 248
Assessment Task 251
Summary 252
Reference 252
MODULE 8

Advanced Python Modules, Objects and Data

Introduction

This Module deals with the advanced lessons about modules, objects and data.
You will be introduced to how incredibly useful the collections of modules is in Python and
it should be your go-to module for a variety of common tasks.

You will also be exposed on how to work with a computer's files and folders in
whichever directory they are in. You will be familiarized not only with the basic
understanding of how to use datetime with Python to work with timestamps in your code.
Understanding of all the methods available for a list in Python. You are also advice that If
you find yourself using these libraries a lot, take a look at the NumPy library for Python,
covers all these capabilities with extreme efficiency. We cover this library and a lot more
in our data science and machine learning courses.

Furthermore, you should feel comfortable using the variety of methods that are
built-in string objects, dictionaries and mathematical operations. You have now a complete
awareness of all the methods available to you for a set object type. This data structure is
extremely useful and is underutilized by beginners, so try to keep it in mind!

Python built-in math library is also introduced for you to play around with in case
you are ever in need of some mathematical operations.

For further information regarding the topics to be presented, you are advice to explore the
Python documentation here: https://docs.python.org/3/library/math.html

181
Learning Outcomes

At the end of this module, students should be able to:

1. Describe and explain profoundly what modules, data and objects are;
2. Ascertain variety of methods that are built-in, string objects, dictionaries
and mathematical operations;
3. Practice and apply variety of methods that are built-in, string objects,
dictionaries and mathematical operations;
4. Implement variety of built-in methods, string objects, dictionaries and
mathematical operations;

Lesson 1. Collections Module (Pierian Data, Udemy, n.d.)

The collections module is a built-in module that implements specialized container data
types providing alternatives to Python’s general purpose built-in containers. We've already
gone over the basics: dict, list, set, and tuple.

Now we'll learn about the alternatives that the collections module provides.

 Counter

Counter is a dict subclass which helps count hashable objects. Inside of it, elements are
stored as dictionary keys and the counts of the objects are stored as the value.

The hash() method returns the hash value of an object if it has one. Hash values are just
integers that are used to compare dictionary keys during a dictionary lookup quickly. An
object is said to be hashable if it has a hash value that remains the same during its lifetime)

Let's see how it can be used:

182
Counter() with lists

Counter with strings

Counter with words in a sentence

183
Common patterns when using the Counter() object
sum(c.values()) # total of all counts
c.clear() # reset all counts
list(c) # list unique elements
set(c) # convert to a set
dict(c) # convert to a regular dictionary
c.items() # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1] # n least common elements
c += Counter() # remove zero and negative counts

 defaultdict

defaultdict is a dictionary-like object which provides all methods provided by a dictionary


but takes a first argument (default_factory) as a default data type for the dictionary. Using
defaultdict is faster than doing the same using dict.set_default method.

A defaultdict will never raise a KeyError. Any key that does not exist gets the value
returned by the default factory.

184
 namedtuple

The standard tuple uses numerical indexes to access its members, for example:

For simple use cases, this is usually enough. On the other hand, remembering which index
should be used for each value can lead to errors, especially if the tuple has a lot of fields
and is constructed far from where it is used. A namedtuple assigns names, as well as the
numerical index, to each member.

Each kind of namedtuple is represented by its own class, created by using the
namedtuple() factory function. The arguments are the name of the new class and a string
containing the names of the elements.

185
You can basically think of namedtuples as a very quick way of creating a new object/class
type with some attribute fields. For example:

We construct the namedtuple by first passing the object type name (Dog) and then
passing a string with the variety of fields as a string with spaces between the field
names. We can then call on the various attributes:

 datetime module

Python has the datetime module to help deal with timestamps in your code. Time values
are represented with the time class. Times have attributes for hour, minute, second, and
microsecond. They can also include time zone information. The arguments to initialize a
time instance are optional, but the default of 0 is unlikely to be what you want.

186
 time

Let's take a look at how we can extract time information from the datetime module. We
can create a timestamp by specifying datetime.time(hour,minute,second,microsecond)

Note: A time instance only holds values of time, and not a date associated with the time.

We can also check the min and max values a time of day can have in the module:

The min and max class attributes reflect the valid range of times in a single day.

 Dates

datetime (as you might suspect) also allows us to work with date timestamps. Calendar
date values are represented with the date class. Instances have attributes for year, month,

187
and day. It is easy to create a date representing today’s date using the today() class
method.

Let's see some examples:

As with time, the range of date values supported can be determined using the min and
max attributes.

Another way to create new date instances uses the replace() method of an existing date.
For example, you can change the year, leaving the day and month alone.

188
 Arithmetic

We can perform arithmetic on date objects to check for time differences. For example:

This gives us the difference in days between the two dates. You can use the timedelta
method to specify various units of times (days, minutes, hours, etc.)

Lesson 2. Math and Random Modules


(Pierian Data, Udemy, n.d.)

Python comes with a built in math module and random module. In this lecture we will give
a brief tour of their capabilities. Usually you can simply look up the function call you are
looking for in the online documentation.
 Math Module Visit this site: https://docs.python.org/3/library/math.html
 Random Module Visit this site: https://docs.python.org/3/library/random.html

We won't go through every function available in these modules since there are so many,
but we will show some useful ones.

 Useful Math Functions


On your Jupyter notebook type the following for you to see the built-in math module

189
 Rounding Numbers

 Mathematical Constants

190
 Random Module

Random Module allows us to create random numbers. We can even set a seed to produce
the same random set every time.

The explanation of how a computer attempts to generate random numbers is beyond the
scope of this course since it involves higher level mathematics. But if you are interested
in this topic check out:

 https://en.wikipedia.org/wiki/Pseudorandom_number_generator
 https://en.wikipedia.org/wiki/Random_seed

 Understanding a seed

Setting a seed allows us to start from a seeded psuedorandom number generator, which
means the same random numbers will show up in a series. Note, you need the seed to be
in the same cell if your using jupyter to guarantee the same results each time. Getting a
same set of random numbers can be important in situations where you will be trying
different variations of functions and want to compare their performance on random values,
but want to do it fairly (so you need the same set of random numbers each time).
In [34]:

191
 Random Integers

 Random with Sequences


Grab a random item from a list

192
 Sample with Replacement

Take a sample size, allowing picking elements more than once. Imagine a bag of
numbered lottery balls, you reach in to grab a random lotto ball, then after marking down
the number, you place it back in the bag, then continue picking another one.

 Sample without Replacement

Once an item has been randomly picked, it can't be picked again. Imagine a bag of
numbered lottery balls, you reach in to grab a random lotto ball, then after marking down
the number, you leave it out of the bag, then continue picking another one.

 Shuffle a list

Note: This effects the object in place!

193
 Random Distributions

Uniform Distribution

Normal/Gaussian Distribution

Lesson 3. Unzipping and Zipping Files


(Pierian Data, Udemy, n.d.)

As you are probably aware, files can be compressed to a zip format. Often people use
special programs on their computer to unzip these files, luckily for us, Python can do the
same task with just a few simple lines of code.

 Create Files to Compress

194
 Zipping Files

The zipfile library is built in to Python, we can use it to compress folders or files. To
compress all files in a folder, just use the os.walk() method to iterate this process for all
the files in a directory.

Create Zip file first , then write to it (the write step compresses the files.)

 Extracting from Zip Files

We can easily extract files with either the extractall() method to get all the files, or just
using the extract() method to only grab individual files.

 Using shutil library

Often you don't want to extract or archive individual files from a .zip, but instead archive
everything at once. The shutil library that is built in to python has easy to use commands
for this:

The shutil library can accept a format parameter, format is the archive format: one of
"zip", "tar", "gztar", "bztar", or "xztar".

195
In [15]: directory_to_zip='C:\\Users\\Marcial\\Pierian-Data-Courses\\Complete-Python-3-Bootcamp\\12-Advanced Python Modules'

Lesson 4. Advanced Numbers (Pierian Data, Udemy, n.d.)

In this lecture we will learn about a few more representations of numbers in Python.

 Hexadecimal

Using the function hex() you can convert numbers into a hexadecimal format:

 Binary

Using the function bin() you can convert numbers into their binary format.

196
 Exponentials

The function pow() takes two arguments, equivalent to x^y. With three arguments it is
equivalent to (x^y)%z, but may be more efficient for long integers.

 Absolute Value

The function abs() returns the absolute value of a number. The argument may be an
integer or a floating point number. If the argument is a complex number, its magnitude is
returned.

 Round

The function round() will round a number to a given precision in decimal digits (default 0
digits). It does not convert integers to floats.

197
Lesson 5. Advanced Strings (Pierian Data, Udemy, n.d.)

String objects have a variety of methods we can use to save time and add functionality.
Let's explore some of them in this lecture:

 Changing case

We can use methods to capitalize the first word of a string, or change the case of the
entire string.

Remember, strings are immutable. None of the above methods change the string in place,
they only return modified copies of the original string.

To change a string requires reassignment:

198
 Location and Counting

 Formatting

The center() method allows you to place your string 'centered' between a provided string
with a certain length. Personally, I've never actually used this in code as it seems pretty
esoteric...

The expandtabs() method will expand tab notations \t into spaces

 is check methods

These various methods below check if the string is some case. Let's explore them:

isalnum() will return True if all characters in s are alphanumeric

isalpha() will return True if all characters in s are alphabetic

199
islower() will return True if all cased characters in s are lowercase and there is at least
one cased character in s, False otherwise.

isspace() will return True if all characters in s are whitespace.

istitle() will return True if s is a title cased string and there is at least one character in s,
i.e. uppercase characters may only follow uncased characters and lowercase characters
only cased ones. It returns False otherwise.

isupper() will return True if all cased characters in s are uppercase and there is at least
one cased character in s, False otherwise.

Another method is endswith() which is essentially the same as a boolean check on s[-1]

200
 Built-in Regular Expressions

Strings have some built-in methods that can resemble regular expression operations. We
can use split() to split the string at a certain element and return a list of the results. We
can use partition() to return a tuple that includes the first occurrence of the separator
sandwiched between the first half and the end half.
In [21]:

Lesson 6. Advanced Sets¶ (Pierian Data, Udemy, n.d.)

In this lecture we will learn about the various methods for sets that you may not have
seen yet. We'll go over the basic ones you already know and then dive a little deeper

 add

add elements to a set. Remember, a set won't duplicate elements; it will only present
them once (that's why it's called a set!)

201
 clear

removes all elements from the set

 copy

returns a copy of the set. Note it is a copy, so changes to the original don't effect the
copy.

 difference

difference returns the difference of two or more sets. The syntax is:

set1.difference(set2)

For example:

202
 difference_update

difference_update syntax is:

set1.difference_update(set2)

the method returns set1 after removing elements found in set2

 discard

Removes an element from a set if it is a member. If the element is not a member, do


nothing.

 intersection and intersection_update

Returns the intersection of two or more sets as a new set.(i.e. elements that are
common to all of the sets.)

203
intersection_update will update a set with the intersection of itself and another.

 isdisjoint

This method will return True if two sets have a null intersection.

 issubset

This method reports whether another set contains this set.

204
 issuperset

This method will report whether this set contains another set.

 symmetric_difference and symmetric_update

Return the symmetric difference of two sets as a new set.(i.e. all elements that are in
exactly one of the sets.)

 union

Returns the union of two sets (i.e. all elements that are in either set.)

205
 update

Update a set with the union of itself and others.

Lesson 7. Advanced Dictionaries


(Pierian Data, Udemy, n.d.)

Unlike some of the other Data Structures we've worked with, most of the really useful
methods available to us in Dictionaries have already been explored throughout this
course. Here we will touch on just a few more for good measure:

 Dictionary Comprehensions

Just like List Comprehensions, Dictionary Data Types also support their own version of
comprehension for quick creation. It is not as commonly used as List Comprehensions,
but the syntax is:

One of the reasons it is not as common is the difficulty in structuring key names that are
not based off the values.

 Iteration over keys, values, and items

Dictionaries can be iterated over using the keys(), values() and items() methods. For
example:

206
 Viewing keys, values and items

By themselves the keys(), values() and items() methods return a dictionary view object.
This is not a separate list of items. Instead, the view is always tied to the original dictionary.
In [6]:

207
Lesson 8. Advanced Lists (Pierian Data, Udemy, n.d.)

In this series of lectures we will be diving a little deeper into all the methods available in a
list object. These aren't officially "advanced" features, just methods that you wouldn't
typically encounter without some additional exploring. It's pretty likely that you've already
encountered some of these yourself!

Let's begin!

 append

You will definitely have used this method by now, which merely appends an element to
the end of a list:

 count

We discussed this during the methods lectures, but here it is again. count() takes in an element
and returns the number of times it occurs in your list:

208
 extend

Many times people find the difference between extend and append to be unclear. So note:

append: appends whole object at end:

extend: extends list by appending elements from the iterable:

Note how extend() appends each element from the passed-in list. That is the key
difference.

 index

index() will return the index of whatever element is placed as an argument. Note: If the
the element is not in the list an error is raised.

209
 insert

insert() takes in two arguments: insert (index,object) This method places the object at the
index supplied. For example:

 pop

You most likely have already seen pop(), which allows us to "pop" off the last element of
a list. However, by passing an index position you can remove and return a specific
element.

 remove

The remove() method removes the first occurrence of a value. For example:

210
 reverse

As you might have guessed, reverse() reverses a list. Note this occurs in place! Meaning
it affects your list permanently.

 sort

The sort() method will sort your list in place:

211
The sort() method takes an optional argument for reverse sorting. Note this is different
than simply reversing the order of items.

Be Careful With Assignment!

A common programming mistake is to assume you can assign a modified list to a new
variable. While this typically works with immutable objects like strings and tuples:

This will NOT work the same way with lists:

What happened? In this case, since list methods like append() affect the list in-place, the
operation returns a None value. This is what was passed to y. In order to retain x you
would have to assign a copy of x to y, and then modify y:

212
213
Assessment Task 8 -1

Work from Home Assignment


Using the string below:

myString = '''To understand the need for creating a class let us consider an example: Let uss
say that you wanted to track the number of dogs which may have different attributes like
breed, and age. If a list is used, the first element could be the dog’s breed while the second
element could represent its age. Let’s suppose there are 100 different dogs, then how would
you know which element is supposed to be which? What if you wanted to add other
properties to these dogs? This lacks organization and it’s the exact need for classes. ‘’’
What to do:
a) import Counter from collections
b) split the string by words
c) get and display the counts for each words
e.g.
string = “How many times does each word show up in in this sentence of word string”
Counter({'How': 1,’many': 1,'times': 2,'does': 1,'each': 1, 'word': 2,'show': 1,'up': 1,'in': 2,'this': 1,
'sentence': 1, ‘of’, 1, ‘string‘:1}]

1) Display the number of the word occurrences and the first 5 topmost common words mentioned
in myString.

2) Display the total number of words in myString

3) Display all the items sets (keywords and values) of all words in myString

4) Display the count of a specific word from myString


Example. In: [('word')]
Out: 2

5) Create a script in Python using your Jupyter Notebook and display the output needed.

Steps: import datetime

given data:
t1 = datetime.time(4, 20, 1)
t2 = datetime.time(6, 20, 1)

Show the different components of object t1


Output:
04:20:01
hour : 4
minute: 20
second: 1
microsecond: 0
tzinfo: None

214
6) Using the combine method get the time difference of the time given below from the
Start time until End time:

Input:
#set Start time
d1 = datetime.time(8,0,0)
print('Start time ..... ', d1)

#set End time


d2 = datetime.time(12,0,0)
print('End time........', d2)
Output:
Start time.....: 08:00:00
End time.......: 12:00:00

Time difference: 4:00:00

7) Create a class with the name Candidate. with the following instance attributes/states:
name, Position. To run add class attribute votes to record all the votes of candidates,
Create a setVotes method, to enter data into the object you are to instantiate. Create
another method name getVotes to access the vote of the candidates and another
method to serve as interface: follow the program structure set below

class Candidate(object):

#class attribute

#contructor/initialization of class Candidate

#method to set votes data

#method to get votes data

#method for interface

#instantiate objects of Candidates

for x in range(10):
dispCandid()
voteCast = int(input('Enter code to cast your vote '))

#set vote
candi1.setVotes(voteCast)

#get vote
candi1.getVotes()
d = dict(Counter(Candidate.votes))

215
Summary

You have now seen how extremely useful the collection of modules is in Python and it
should be your go-to module for a variety of common tasks.

You are also aware now of how to work with a computer's files. How to zip and unzipped
files and find folders in whichever directory they are in. Remember that the os module
works for any operating system that supports Python, which means these commands will
work across Linux, Mac, or Windows without need for adjustment.

Now, you are also familiar with the basic understanding of how to use datetime with Python
to work with timestamps in your code. Understanding of all the methods available for a list
in Python. You are also advice that If you find yourself using these libraries a lot, take a
look at the NumPy library for Python, covers all these capabilities with extreme efficiency.
We cover this library and a lot more in our data science and machine learning courses.

Furthermore, you should now feel comfortable using the variety of methods that are built-
in string objects, dictionaries and mathematical operations. You have now a complete
awareness of all the methods available to you for a set object type. This data structure is
extremely useful and is underutilized by beginners, so try to keep it in mind!

Reference

GitHub - Pierian-Data/Complete-Python-3-Bootcamp: Course Files for Complete


Python 3 Bootcamp Course on Udemy. (n.d.). Retrieved September 11,
2020, from https://github.com/Pierian-Data/Complete-Python-3-Bootcamp

216
MODULE 9
Working with Images, PDFs in Python

Introduction

This module will introduce you to work on images in Python includingseveral


packages you will need for working with images.

This module introduces you to the basic tools for reading images, cropping and
scaling images, resizing, flipping, copying and pasting and saving results, and other basic
manipulation in images.

You will be introduced, also to one of the most popular and considered as default
library of python for image processing is Pillow. Pillow is an updated version of the Python
Image Library or PIL and supports a range of simple and advanced image manipulation
functionality.

PDF will also be introduced as part of this module. The Portable Document Format,
or PDF, is a file format that can be used to present and exchange documents reliably
across operating systems. You can work with a PDF in Python by using the packages
usable in Python designed for PDF files.

Learning Outcomes

At the end of this module, students should be able to:

1. Discuss and describe how to work with images;


2. Discuss and describe how to work with PDF files;
3. Manipulate images and PDF using packages and functionalities; and
4. Apply and demonstrate images editing, resizing, converting and other;

217
Lesson 1. Working with Images

By leveraging the power of some common libraries that you can install, such as PILLOW,
Python gains the ability to work with and manipulate images for simple tasks. You can
install Pillow by running:

pip install pillow

In case of any issues, you can refer to their official documentation on installation. But for
most computers, the simple pip install method should work.

Note: When working with images in the jupyter notebook, you may get the following
warning:

IOPub data rate exceeded.


The notebook server will temporarily stop sending output
to the client in order to avoid crashing it.
To change this limit, set the config variable
`--NotebookApp.iopub_data_rate_limit`.

If you get this warning, try stopping the notebook at the command line, then restarting it
with:

jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10

** At the command line. Basically this adds a "flag" that the limit should be raised during
this session of jupyter notebook that you are running.**

 Working with Pillow Library


Note: before you can work with this topic, you are encourage to download any image in your
working directory if you can not find the image set as an example and follow the steps cited here
in the process.

218
Opening Images

You can use Pillow to open image files. For a jupyter notebook, to show the file simply
type the variable name holding the image. For other IDEs , the image variable will have
a .show() method.

Image Information¶

219
 Cropping Images

To crop images (that is grab a sub section) you can use the crop() method on the image
object. The crop() method returns a rectangular region from this image. The box is a 4-
tuple defining the left, upper, right, and lower pixel coordinate.

Note! If you take a look at the documentation string, it says the tuple you pass in is defined
as (x,y,w,h). These variables can be a bit deceiving. It’s not really a height or width that is
being passed, but instead the end coordinates of your width and height.

All the coordinates of box (x, y, w, h) are measured from the top left corner of the image.
Again, all 4 of these values are coordinates!

For the mac image this isn't a very useful demonstration. Let's use another image instead:

220
Now let's attempt to grab some of the top pencils from the corner

221
Now let's try the pencils from the bottom

222
Now let's go back to the mac photo and see if we can only grab the computer itself:

223
 Copying and Pasting Images

We can create copies with the copy() method and paste images on top of others with the
paste() method.

224
 Resizing

You can use the resize() method to resize an image

Can also stretch and squeeze

225
 Rotating Images

You can rotate images by specifying the amount of degrees to rotate on the rotate()
method. The original dimensions will be kept and "filled" in with black. You can optionally
pass in the expand parameter to fill the new rotated image to the old dimensions.

 Transparency

We can add an alpha value ( RGBA stands for Red, Green, Blue, Alpha) where values can
go from 0 to 255. If Alpha is 0 the image is completely transparent, if it is 255 then it’s
completely opaque.

You can create your own color here to check for possible values:
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Colors/Color_picker_tool

We can adjust image alpha values with the put alpha() method:

226
227
 Saving Images
Let's save this updated "blue" image as 'purple.png' in this folder.

Let's check to make sure that worked

228
Lesson 2. Working with PDF Files
Often you will have to deal with PDF files. There are many libraries in Python for working
with PDFs, each with their pros and cons, the most common one being PyPDF2. You can
install it with (note the case-sensitivity, you need to make sure your capitilization matches):

pip install PyPDF2

Keep in mind that not every PDF file can be read with this library. PDFs that are too blurry,
have a special encoding, encrypted, or maybe just created with a particular program that
doesn't work well with PyPDF2 won't be able to be read. If you find yourself in this situation,
try using the libraries linked above, but keep in mind, these may also not work. The reason
for this is because of the many different parameters for a PDF and how non-standard the
settings can be, text could be shown as an image instead of a utf-8 encoding. There are
many parameters to consider in this aspect.

As far as PyPDF2 is concerned, it can only read the text from a PDF document, it won't
be able to grab images or other media files from a PDF.

 Working with PyPDF2


Note: before you can work with this topic, download any iPDF file in your working
directory if you can not find the PDF set as an example and follow the steps stated in
the process.

Let's being showing the basics of the PyPDF2 library.

Reading PDFs

Similar to the csv library, we open a pdf, then create a reader object for it. Notice how we
use the binary method of reading , 'rb', instead of just 'r'.

229
We can then extract the text

 Adding to PDFs

We can not write to PDFs using Python because of the differences between the single
string type of Python, and the variety of fonts, placements, and other parameters that a
PDF could have.

What we can do is copy pages and append pages to the end.

230
Now we have copied a page and added it to another new document!

Simple Example

Let's try to grab all the text from this PDF file:

231
That is all for PyPDF2 for now, remember that this won't work with every PDF file and is

limited in its scope to only text of PDFs.

232
Assessment Task 9.1

Test your knowledge.

Work on image
Download the nature image from the link below
https://thumbs.dreamstime.com/b/environment-earth-day-hands-trees-growing-
seedlings-bokeh-green-background-female-hand-holding-tree-nature-field-gra-
130247647.jpg
Store it on your Jupyter notebook folder (your work area directory) and do the
needed modification on the image.

1) Load and show the image with Pillow from your directory where the image
was stored.
e.g. from PIL import Image
#Load the image
image = Image.open('c:\nature.jpg')

2) Get basic details about the image


image.format
image.mode
image.size
Output:
JPEG
RGB
(800, 484)
233
3) Cropping image

#load image
#crop image
#Save image to same directory
#show cropped image

4) Rotate the cropped image

5) Flip image of left and right

234
Summary

Basic ideas and functionalities have been discussed to you. By now understanding and
confidence are evident in you. You will be able to manipulate images and PDF files
independently. Constant exercises and practices will help you boost your knowledge and
expertise in manipulation images and PDF files. Continue to learn.

References
Udemy, (n.d) Complete-Python-3-Bootcamp-master/Complete-Python-3-Bootcamp-master/07-
Errors%20and%20Exception%20Handling/01- Errors%20and%20Exceptions%20Handling.ipynb,
https://www.udemy.com/course/complete-python-bootcamp/learn/lecture/9478394#content

235
MODULE 10

GUI: An Introduction

Introduction

For most software systems, a Graphical User Interface (GUI) is an expected


part of the package. I know that most of you are familiar with such interfaces: the windows,
buttons, and menus that we use to interact with software programs.

In this module, we will learn how to make Python scripts in programs modules for GUI
interface. In this module, we will focus on and have a quick understanding about tkinter
library and teach you the basics. Interfaces are kept simple on purpose to master
fundamentals of GUI. Python with tkinter is the fastest and easiest way to create the GUI
applications. Creating a GUI using tkinter shall be an easy task for everyone.

Learning Outcomes

At the end of this module, students should be able to:

1. Describe importing the module – tkinter


2. Create the main window (container)
3. incorporate any number of widgets to the main window
4. Apply confidently the event Trigger on the widgets.

Lesson 1. Introduction to GUI with Tkinter in Python


(Aditya, 2019)

In this module, you are going to learn how to create GUI apps in Python. You'll also learn
about all the elements needed to develop GUI apps in Python.

Most of you write a code and run it in a Jupyter Notebook or in PyCharm an IDE (Integrated
Development Environment), and the code produces an output based on what you expect
out of it either on the terminal or on the IDE itself. However, what if you want your system

236
to have a fancy looking user-interface or maybe your application (use-case) requires you
to have a GUI.

GUI is nothing but a desktop app that provides you with an interface that helps you to
interact with the computers and enriches your experience of giving a command
(command-line input) to your code. They are used to perform different tasks in desktops,
laptops, and other electronic devices, etc.

Some of the applications where the power of GUI is utilized are:


 Creating a Calculator which would have a user-interface and functionalities that
persists in a calculator.
 Text-Editors, IDE's for coding are on a GUI app.
 Sudoku, Chess, Solitaire, etc.., are games that you can play are GUI apps.
 Chrome, Firefox, Microsoft Edge, etc. used to surf the internet is a GUI app.

Another interesting use-case would be - A GUI for controlling a Drone from your laptop,
and the GUI would probably have buttons to maneuver the Drone along with a screen that
would show the camera feed captured by the Drone in a real-time.

Let's see some of the frameworks that Python provides to develop a GUI:

 PyQT is one of the favored cross-platform Python bindings implementing the Qt


library for the Qt application development framework. Nokia primarily owns Qt.
Currently, PyQT is available for almost all operating systems like Unix/Linux,
Windows, Mac OS X. It blends the best of Python and Qt and provides flexibility to
the programmer to decide whether to create a program by writing a pure python
code or use Qt Designer to create visual dialogs.

 Kivy is for the creation of new user interfaces and is an OpenGL ES 2 accelerated
framework. Much like PyQt, Kivy also supports almost all platforms like Windows,
MacOSX, Linux, Android, iOS. It is an open-source framework and comes with
over 20 pre-loaded widgets in its toolkit.

 Jython is a Python port for Java, which gives Python scripts seamless access to
Java class libraries on the local machine.

237
 WxPython, initially known as WxWindows (now as a WxWidgets library), is an
open-source abstract-level wrapper for cross-platform GUI library. It is
implemented as a Python expansion module. With WxPython, you, as a developer,
can create native applications for Windows, Mac OS, and Unix.

 PyGUI is a graphical application cross-platform framework for Unix, Macintosh,


and Windows. Compared to some other GUI frameworks, PyGUI is by far the
simplest and lightweight of them all, as the API is purely in sync with Python. PyGUI
inserts very less code between the GUI platform and Python application; hence,
the display of the application usually displays the natural GUI of the platform.

And finally, the framework that is the discussion for today's tutorial Tkinter!

 Tkinter commonly comes bundled with Python, using Tk and is Python's standard
GUI framework. It is famous for its simplicity and graphical user interface. It is
open-source and available under the Python License.

Note: Tkinter comes pre-installed with Python3, and you need not bother about installing
it.

Now, let's build a very simple GUI with the help of Tkinter and understand it with the help
of a flow diagram.

Figure 10.1 Flow Diagram for Rendering a Basic GUI

Let's break down the above flow diagram and understand what each component is
handling!
 First, you import the key component, i.e., the Tkinter module.

238
 As a next step, you initialize the window manager with the tkinter.Tk() method and
assign it to a variable. This method creates a blank window with close, maximize,
and minimize buttons on the top as a usual GUI should have.
 Then as an optional step, you will Rename the title of the window as you like
with window.title(title_of_the_window).
 Next, you make use of a widget called Label, which is used to insert some text into
the window.
 Then, you make use of Tkinter's geometry management attribute called pack() to
display the widget in size it requires.
 Finally, as the last step, you use the mainloop() method to display the window until
you manually close it. It runs an infinite loop in the backend.

After running the above code in a terminal, you shall see a similar output, as shown below.

Similarly, you could have a widget Button, and the GUI will display a button instead of
some text (Label).

Though you have already learned to use Widgets in Tkinter but let's find out which other
widgets are available in Tkinter and the functioning of each of them.

239
Lesson 2. Widgets (Aditya, 2019)
Widgets are similar in spirit to elements in HTML. You will find different types of widgets
for different types of elements in the Tkinter. They are standard GUI elements and
provide the user with controls like buttons, text, menus, and text boxes.

Let's understand all of these widgets in Tkinter, along with an example (Source).
 Button: Button widget has a property for switching on/off. When a user clicks the
button, an event is triggered in the Tkinter.

Syntax: button_widget = tk.Button(widget, option=placeholder)

where widget is the argument for the parent window/frame while option is a
placeholder that can have various values like foreground & background color, font,
command (for function call), image, height, and width of button.

 Canvas: Canvas is used to draw shapes in your GUI and supports various drawing
methods.

Syntax: canvas_widget = tk.Canvas(widget, option=placeholder)

where widget is the parameter for the parent window/frame while option is a
placeholder that can have various values like border-width, background color,
height and width of widget.

 Checkbutton: Checkbutton records on-off or true-false state. It lets you can select
more than one option at a time and even leave it unchecked.

Syntax: checkbutton_widget = tk.CheckButton(widget, option=placeholder)

where widget is the parameter for the parent window/frame while option is a
placeholder that can have various values like title, text, background & foreground
color while widget is under the cursor, font, image, etc.

 Entry: Entry widget is used to create input fields or to get input text from the user
within the GUI.

Syntax: entry_widget = tk.Entry(widget, option=placeholder)

240
where widget is the parameter for the parent window/frame while option is a
placeholder that can have various values like border-width, background color,
width & height of button etc.

 Frame: Frame is used as containers in the Tkinter for grouping and adequately
organizing the widgets.

Syntax: frame_widget = tk.Frame(widget, option=placeholder)

where widget is the parameter for the parent window/frame while option is a
placeholder that can have various values like border-width, height & width of
widget, highlightcolor (color when widget has to be focused).

 Label: Label is used to create a single line widgets like text, images, etc.
Syntax: label_widget = tk.Label(widget, option=placeholder)

where widget is the parameter for the parent window/frame while option is a
placeholder that can have various values like the font of a button, background
color, image, width, and height of button.

You can find the complete list of widgets at the official Python documentation.

Lesson 3. Geometry Management (Aditya, 2019)


All widgets in Tkinter have some geometry measurements. These geometry
measurements allow you to organize the widgets and throughout the parent frames or
parent widget area.

One of the geometry management classes, i.e., pack(), has already been covered here.

For this purpose, Tkinter provides you with three main geometry manager classes:

 pack(): It organizes the widgets in a block manner, and the complete available
width is occupied by it. It's a conventional method to show the widgets in the
window.
 grid(): It organizes the widgets in a table-like structure. You will learn about it in
detail later in this tutorial.

241
 place(): Its purpose is to place the widgets at a specific position as instructed by
the user in the parent widget.

 Organizing Layout and Widgets


In this section of the tutorial, you will make use of both geometry and widgets, and let's
see the magic of Tkinter.

To arrange the layout in the window, you will use a Frame widget class. Let's create a
simple program to see how the Frame works.
 You will define two frames - top and bottom with the help of the pack class. The
Frame class will help in creating a division between the window. Basically, a
single-window will be replicated twice as top and bottom in the form of a Frame.
 Finally, you will create four buttons in the window, two for each frame. You can
name and color your buttons as you like as a parameter.

Let's run the above code and see the output.

242
 Grid
Much like a Frame, a grid is another way to organize the widgets. It uses the Matrix row-
column concept. Let's draw some analogy between the grid class and the row-column
idea with the help of the below diagram.

Grid primarily takes two parameters row and column. As shown in the above figure,
imagine 00 corresponds to the first button while 01 to the second. And to place two
buttons side-by-side, grid will take row and column parameters as 00 and 01,
respectively.

Let's make use of checkbutton to understand how grid class works. You will define two
checkbuttons and specify some text for both the buttons. The state of the check buttons
will be decided by the onvalue and offvalue while the current state of the checkbutton will
be tracked by IntVar(), which will be stored in a separate variable. When
the offvalue=1 and the onvalue=0 corresponding checkbutton will be ticked.

Now coming to grid class, you will pass a parameter row, which will position the button in
the first row if row=0 and in the second row if row=1.

243
Let's run this code and see the output.

Let's take another example to understand the grid. In this example, you will also pass
a column as a parameter along with the row.

244
Let's look at the output of the above code!

How simple it was, and it looks identical to one written with HTML.

Lesson 4. Binding or Command Functions (Udemy, n.d.)


Binding or Command functions are those who are called whenever an event occurs or is
triggered.

Let's take an example to understand binding functions.

You will define a button which, when clicked, calls a function called DataCamp_Tutorial.
Further, the function DataCamp_Tutorial will create a new label with the text GUI with
Tkinter!.

Let's run the code and observe the output.

245
Apart from invoking binding functions with a mouse click, the events can be invoked with
a mouse-move, mouse-over, clicking, scrolling, etc.

Let's now look at the bind function, which provides you the same functionality as above.

 Mouse Clicking Event via the Bind Method


The Bind method provides you with a very simplistic approach to implementing the mouse
clicking events. Let's look at the three pre-defined functions which can be used out of the
box with the bind method.

Clicking events are of three types leftClick, middleClick, and rightClick.

 <Button-1> parameter of the bind method is the left-clicking event, i.e., when you
click the left button, the bind method will call the function specified as a second
parameter to it.

 <Button-2> for middle-click

 <Button-3> for right-click

Now, you will learn how to call a particular function based on the event that occurs.

 Run the following program and click the left, middle, right buttons to call a specific
function.

 That function will create a new label with the specified text.

246
Let's run the above code.

Lesson 5. Alert Boxes (Udemy, n.d.)


You can create alert boxes in the Tkinter using the messagebox method. You can also
create questions using the messasgebox method.

Here you will create a simple alert-box and also create a question. For generating an alert,
you will use messagebox function showinfo. For creating a question, you will use
the askquestion method, and based on the response to the question, you will output
a Label on the GUI.

247
Let's quickly run the above code and see the output.

Lesson 6. Rendering Images (Udemy, n.d.)


If you have been able to follow along until here, then, adding images and icons to the GUI
should be a piece of cake. All you need to do is use the PhotoImage method of Tkinter
and pass the file_path as the parameter to it.

So, without any further ado, let's quickly write a code for displaying an image on the GUI.

248
Figure 10.2 Rendering Images

Well done if you were able to follow along till here!

249
For more information on GUI using tkinter check out the following:

 https://www.tutorialspoint.com/python/python_gui_programming.htm

 https://www.python-course.eu/python_tkinter.php

250
Assessment Task 10.1

Test your knowledge.


1) Create a dialog box with a 400x200 dimension shown below:

2) Create a dialog box with a 400x200 dimension with Label option to expand=YES
shown below:

3) Create a dialog box with a 400x200 dimension, button to print label “Laguna
University” when clicked. Follow other options e.g. color, as shown below:

251
Summary

Congratulations on finishing this module!

Based on your learnings from this module, you are ready to make some simple GUI apps.
You have to learn more methods for styling and interaction with the objects in a GUI.

One useful exercise would be to try developing applications similar to creating a calculator
(modified calculator for IT 2108 classes) that will help boost your confidence and give you
a much more holistic idea of what all is possible with GUI in Tkinter.

References

Aditya (2019). Tutorial) Introduction to GUI With TKINTER in PYTHON. (2020).


Retrieved 26 November 2020, from
https://www.datacamp.com/community/tutorials/gui-tkinter-Python

Udemy, (n.d.) Complete Python Bootcamp: From Zero to Hero in Python.


Retrieved August 17, 2020, from https://www.udemy.com/course/complete-
python-bootcamp/learn/lecture/9388522#content

- END OF MODULE FOR FINALS PERIOD -

SUBMISSION OF ASSESSMENT TASKS AND EXAMINATION FOR FINALS PERIOD WILL BE

ANNOUNCED VIA iLearnU LMS or GC

MAKE SURE TO CHECK THE DATES AND DO NOT FORGET TO TAKE IT AS SCHEDULED.

252

You might also like