Professional Documents
Culture Documents
ITP107-Final Draft Module (20240529092814)
ITP107-Final Draft Module (20240529092814)
ITP107-Final Draft Module (20240529092814)
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
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
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;
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)
182
Counter() with lists
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
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.
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.)
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.
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
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.
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
193
Random Distributions
Uniform Distribution
Normal/Gaussian Distribution
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.
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.)
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.
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'
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.
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...
is check methods
These various methods below check if the string is some case. Let's explore them:
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.
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]:
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
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
set1.difference_update(set2)
discard
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
204
issuperset
This method will report whether this set contains another set.
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
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.
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:
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
211
The sort() method takes an optional argument for reverse sorting. Note this is different
than simply reversing the order of items.
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:
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
Laboratory Exercise
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.
1) Display the number of the word occurrences and the first 5 topmost common words mentioned
in myString.
3) Display all the items sets (keywords and values) of all words in myString
5) Create a script in Python using your Jupyter Notebook and display the output needed.
given data:
t1 = datetime.time(4, 20, 1)
t2 = datetime.time(6, 20, 1)
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)
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
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
216
MODULE 9
Working with Images, PDFs in Python
Introduction
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
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:
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:
If you get this warning, try stopping the notebook at the command line, then restarting it
with:
** 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.**
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
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.
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):
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.
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.
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
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')
#load image
#crop image
#Save image to same directory
#show cropped image
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
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.
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:
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 and offvalue while the current state of the checkbutton will
be tracked by , which will be stored in a separate variable. When
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.
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!.
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.
<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.
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.
Here you will create a simple alert-box and also create a question. For generating an alert,
you will use function showinfo. For creating a question, you will use
the method, and based on the response to the question, you will output
247
Let's quickly run the above code and see the output.
So, without any further ado, let's quickly write a code for displaying an image on the GUI.
248
Figure 10.2 Rendering Images
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
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
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
MAKE SURE TO CHECK THE DATES AND DO NOT FORGET TO TAKE IT AS SCHEDULED.
252