0% found this document useful (0 votes)
18 views50 pages

Unit 412

Uploaded by

245123742004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views50 pages

Unit 412

Uploaded by

245123742004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Programming for Problem Solving Using Python MVSREC

MATURI VENKATA SUBBA RAO (MVSR) ENGINEERING COLLEGE


NADERGUL, HYDERABAD-501510
(Sponsored by Matrusri Education Society, Estd.1980)
An Autonomous Institution
Approved by AICTE & Affiliated to Osmania University, Estd.1981
ISO 9001:2015 Certified Institution, Accredited by NAAC
website: www.mvsrec.edu.in

COURSE MATERIAL

For

PROGRAMMING FOR PROBLEM SOLVING USING


PYTHON
Subject Code: U21ESN03CS
Class: B.E- First Year, Sem-2
Acad.Year: 2021-22 Even Semester

Notes prepared by
P. Phani Prasad
Assistant Professor,
Department of CSE,
MVSREC

B.E- First Year, Sem-2 Page: 1


Programming for Problem Solving Using Python MVSREC

UNIT-IV

TOPICS COVERED
I. Exception Handling
1. Introduction to Errors & Exceptions
2. Brief about Built -in exceptions
3. Handling an exception using try, except blocks
4. Using multiple except blocks
5. Using except block without exception
6. else block
7. Finally block
8. Raising and instantiating an exception
9. Custom exceptions
II. File Handling
1. Introduction to files
2. Types of files
3. Modes of files
4. File operations
5. File positions
6. File paths
7. Renaming and deleting a file
III. GUI Programming
1. Introduction to GUI
2. Difference between terminal based applications and GUI applications
3. Creating a GUI window using Tkinter module
4. Tkinter widgets
a. Label
b. Entry
c. Button
d. Checkbutton
e. RadioButton
5. Tkinter geometry management
6. Event driven programming
7. Displaying notification dialog boxes
8. Example programs
a. Creating a Login application
b. Building a registration form

B.E- First Year, Sem-2 Page: 2


Programming for Problem Solving Using Python MVSREC

PART-I: EXCEPTION HANDLING

1. Introduction to Errors & Exceptions


What is an error?
An error is something giving a wrong instruction by violating the basic rules of
programming which python fails to execute.
Getting errors is common for users who learn a new programming language. Infact users can
learn and understand the language principles better from errors.
Types of errors:
a. Syntax error: An error occurs during interpretation of a python program. When a wrong
instruction is given by violating the rules of the programming language, python throws
this error and stops further interpretation of statements.
Examples: Giving uppercase letters instead of lowercase, forgetting to close parentheses
() or blocks ie., :, [] , forgetting to put single/double quotes for strings, giving
unnecessary spaces etc.
Observe the below statement that produces syntax error.

b. Logical error: An error that occurs due to producing a wrong result for the given
problem.
For example, producing division results if the given problem is to compute addition
operation.
Logical errors come during the execution of the program. They occur because of
misunderstanding of the given problem by users.
c. Runtime error: An error that occurs when python fails to execute an instruction and
causes abnormal termination of the program.
What is an Exception?
An exception is a runtime error that interrupts and deviates the normal flow of the program
execution and leads to abnormal termination of program.
➔ When an exception occurs at a line,python fails to take a necessary action on that line.
This causes the program to terminate abruptly without executing further error free lines.
➔ To stop the program from abnormal termination, an exception must be handled by
suspecting it.
➔ Python provides many built-in exception handling classes based on the nature of
exception.
➔ For example, the below line throws ZeroDivisionError when trying to divide a number
with zero.

B.E- First Year, Sem-2 Page: 3


Programming for Problem Solving Using Python MVSREC

2. Brief about Built -in exceptions


● Python supports many built-in exceptions classes to handle different types of runtime
errors.
● All exceptions are derived from parent class BaseException which is a subclass of
object.
● Syntax errors ,indentation errors ,built-in exceptions and user-defined exceptions are
derived from BaseException class. Below is the hierarchy structure.



Few of the built-in exceptions are described below.

Name of exception description example

ZeroDivisionError Attempting to divide


any value by zero

IndexError Attempting to access a


list value out of index
range

B.E- First Year, Sem-2 Page: 4


Programming for Problem Solving Using Python MVSREC

NameError Trying to access a


variable which is not
defined

ValueError When a function fails to


convert a given value to
specific type

TypeError When an operation fails


to compute by giving
wrong operands

KeyError Trying to access a


non-existing key in a set
or dictionary

ModuleNotFounderr Trying to load a module


or that doesn’t exist

AttributeError Trying to access an


attribute which is not
defined in a class

RecursionError Occurs when the maximum threshold level of recursion computation


exceeds. Below is the example with output

B.E- First Year, Sem-2 Page: 5


Programming for Problem Solving Using Python MVSREC

EOFError Occurs when pressed


Ctrl+D from the
keyboard without
reading data

FileNotFoundError Trying to read a file that


doesn’t exist

KeyboardInterrupt Occurs when pressed


Ctrl+C from the
keyboard while program
is under execution

3. Handling an exception using try, except blocks


● Python provides two special blocks to handle any kind of built-in exception or user
defined exception. They are:
○ “try” block: this block contains all the statements that leads to error during
execution of the program.
■ When an error occurs, python generates a corresponding error object at
that line and searches for a proper handler to handover the error.
■ If proper handler found, control jumps to handler block and executes
handling statements and continues to other below statement execution
■ If no proper handler is found, the program terminates abnormally from the
error line.
○ “except” block: This block is called an error handler block. Errors caused in try
block will be distributed to this block and handled here.
■ This block prints the error information and the class that generated the
error message.
■ Control once entered into the except block will never go back to try block
again. It executes the below pending statements in the program.
■ An except block can handle more than one exception.

B.E- First Year, Sem-2 Page: 6


Programming for Problem Solving Using Python MVSREC

○ Syntax of using try and except block:


Syntax-1
try:
#statements
except ExceptionName:
#statements
Syntax-2
try:
#statements
except ExceptionName as ExceptionVariable:
#statements
○ Examples

Example-1 Output-1 Output-2

Example-2 Output-1 Output-2

4. Using multiple except blocks


● We can handle multiple exceptions at a time by specifying multiple except blocks.
● First we put all statements that cause exceptions in a try block.
● Next we write each except block that handles each exception that causes in try block.
● We print each error information using the exception variable in the except block.

B.E- First Year, Sem-2 Page: 7


Programming for Problem Solving Using Python MVSREC

Syntax
try:
#statements
#error statement-1
#error statement-2

#error statement-N
except Exception1 as errorVariable-1:
#statements to handle error statement-1
except Exception2 as errorVariable-2:
#statements to handle error statement-2
….
except ExceptionN as errorVariable-N:
#statements to handle error statement-N

Example :
The below program handles 3 exceptions:ValueError, ZeroDivisionError, IndexError

output-1 output-2 output-3 output-4

B.E- First Year, Sem-2 Page: 8


Programming for Problem Solving Using Python MVSREC

Using single “except” block to handle multiple exceptions:


→ Writing multiple except blocks for handling many exceptions will definitely increase the
length of the code.
→ so instead of writing each except block for handling each exception we use only one
except block to handle many exceptions using below syntax.
Syntax:
try:
#statements
#error statement-1
#error statement-2

#error statement-N
except (Exception1,Exception-2,Exception-3,...,Exception-N) as
errorVariable:
#statements to handle error statement-1
#statements to handle error statement-2

#statements to handle error statement-N
In the above syntax, we specify all the known possible exceptions as a tuple of exceptions in the
except block.
When an exception occurs, the except block handles that specific exception and its error
information is accessed from errorVariable.
But if the error occurred in try block is not identified in tuple, then program terminates abruptly.
Example:
The below program handles 3 exceptions:ValueError, ZeroDivisionError, IndexError using
single except block

B.E- First Year, Sem-2 Page: 9


Programming for Problem Solving Using Python MVSREC

output-1 output-2 output-3 output-4

Handling unknown exceptions:


● Above two syntaxes handle known exceptions.That means the user can suspect the type
of exception while running the program.
● But in some cases, we may not guess the exact exception arises in the program. In such
cases,the program may terminate abruptly due to improper handling of exceptions.
● So, to handle both the known and unknown exceptions in the program, we use the parent
class BaseException in the except block.
● The BaseException is the parent class for all kinds of exceptions. So when a specific
exception occurs, the BaseException performs a runtime polymorphism and handles that
specific exception.
● For example if IndexError occurs, BaseException behaves as IndexError.
● If ValueError comes, BaseException behaves as ValueError. This continues so on for all
kinds of exceptions.
● To know what kind of error is handled ,we use repr() function.
● repr() is a built-in function that returns Exception Name and Error information.

B.E- First Year, Sem-2 Page: 10


Programming for Problem Solving Using Python MVSREC

Example:
The below program handles 3 exceptions:ValueError, ZeroDivisionError, IndexError using
BaseException

Output-1

Output-2

Output-3

B.E- First Year, Sem-2 Page: 11


Programming for Problem Solving Using Python MVSREC

Output-4

5. Using except block without exception


● An except block can be used without specifying any exception name or
exceptionVariable.
● This type of except block is to handle any error and specify a general error message for
all kinds of errors that arise in the try block.
Syntax:
try:
#statements
#error statement-1
#error statement-2

#error statement-N
except:
#statements to handle any error

Example: The below program raises 3 types of errors but except block prints common error
message to all types of errors

Output -1 Output -2

B.E- First Year, Sem-2 Page: 12


Programming for Problem Solving Using Python MVSREC

6. else block
● “else” is a special block which executes only when all the statements in the try block are
executed without raising any exception.
● “else” block ensures that the try block is executed successfully and it is exception free.
● “else” block is an optional block which should be written immediately after the except
block.
● “else” block will be skipped from the execution if atleast one exception is raised in the try
block.
● Syntax:
try:
#statements
except :
#statements
else:
#statements
● Example:

Output -1 Output -2

B.E- First Year, Sem-2 Page: 13


Programming for Problem Solving Using Python MVSREC

7. “finally” block
● “Finally” block is a special block that executes irrespective of error occurs in the
program.
● That means , this block will execute if error occurs in the program and if errors do not
occur in the program.
● The main purpose of this block is to perform clean up activity. That means releasing of
resources utilized by the program such as closing the opened file, disconnecting database
connections, disconnecting network communication etc.
● If any error occurs in the program, the resources used by the program will run
continuously until the program abruptly terminates and that is of no use.
● So the “finally” block completes this clean up activity before terminating the program.
● “finally” executes in three cases:
○ If no error occurs,try and finally executes
○ If errors occurs and handled, except block and finally block executes
○ If error occurs , but not handled, finally the block executes and the program
terminates abruptly.
● Syntax

Syntax-1 Syntax-2 Syntax-2

try: try: try:


#try statements #try statements #try statements
except: except: finally:
#except statements #except statements #statements
else: finally:
#else statements #statements
finally:
#statements

● Example-1 (Without any exception in try)

B.E- First Year, Sem-2 Page: 14


Programming for Problem Solving Using Python MVSREC

Output

● Example-2 (With an exception in try,but handled )

B.E- First Year, Sem-2 Page: 15


Programming for Problem Solving Using Python MVSREC

Output

● Example-3 (With an exception in try,but not handled )

Output

8. Raising and instantiating an exception


● Python allows us to generate an exception intentionally or wantedly by the user though
there is no scope of error occurrence in the program.
● The keyword “raise” is used to generate an exception on demand by the user.
● It allows generating both built-in and custom exceptions.
● During generation of exceptions, we can send user defined messages to the “except”
block to display error messages.
● To generate an exception, first an exception object is created and that exception is thrown
or distributed to the “except” block using the “raise” keyword.

B.E- First Year, Sem-2 Page: 16


Programming for Problem Solving Using Python MVSREC

● Below is the syntax to raise an exception


try:
#statements
raise ExceptionName([Error Message])
#statements
except ExceptionName:
#statements
● Note: Error Message in square brackets is an optional
● Example

Output-1 Output-2 Output-3

9. Custom exceptions
● The process of creating our own exceptions is known as custom exceptions or user
defined exceptions.
● Python supports many built-in exceptions, but these exceptions may not be reasonable to
use in real time applications that involve more human interactions.
● For example, assume you went to an ATM to withdraw money from account-X. If
account-X has Rs.500 amount as balance but withdrawing Rs.1000 then the system
should display a reasonable message “Insufficient balance in account” but not IndexError
or ValueError or something else.
● So to create such kind of user defined error messages we use custom exceptions.

B.E- First Year, Sem-2 Page: 17


Programming for Problem Solving Using Python MVSREC

● We can create many custom exceptions in a program.


● Steps to create custom exceptions:
○ Create a user-defined class with a name
○ Inherit the above class from parent class BaseException
○ Do any of the following or both:
■ Define __init__() function and initialize custom message
■ Define __str__() function and print custom message
○ Now in the application, inside the try block, create an object of above class and
raise the custom exception.
○ Handle the custom exception in except block
● Syntax
class custom(BaseException):
def __init__(self,msg):
self.msg=msg
def __str__(self):
#statements
#actual program
try:
#statements
# raise custom(any string message)
#statements
except (custom) as c:
#statements
● Example

B.E- First Year, Sem-2 Page: 18


Programming for Problem Solving Using Python MVSREC

Output -1

Output-2

B.E- First Year, Sem-2 Page: 19


Programming for Problem Solving Using Python MVSREC

PART - II : FILE HANDLING


1. Introduction to files
What is a file? A file is a collection of data stored with a named location in secondary
storage devices like hard disk,pendrive, CD-ROM etc.
Need of file:
Files are used to
● Store huge amount of data range from bytes to Gigabytes or more
● Store data permanently in secondary storage devices.
Usually when a program displays results after its execution. But the results are
stored in volatile memory RAM.
So results and data will be lost after power off the computer.
Inorder to store the data and results permanently,we store data permanently in non-volatile
memories like hard disks etc.
Data will be available even power off the computer.
2. Types of files
Most of the programming languages support files. We can create two types of files.
a. Text files:
i. These files store the data in the form of characters.
ii. This type of files are human readable
iii. Occupies more amount of memory for storing data
iv. Editors and word processors are required to create these files.
v. Examples :
1. .txt (text file)
2. .docx (word document file)
3. .xlsx (excel sheet file)
4. .html (html web document file)
5. .xml (xml web document file)
6. Any high level language program (.c, .cpp, .py , .java etc)
b. Binary files:
i. These files store data in the form of bytes i.e 0’s and 1’s
ii. This type of files are not human readable
iii. Occupies less amount of memory for storing data
iv. A suitable application is required to operate on these files
v. Examples :
1. .jpeg (image file)
2. .png (image file)
3. .mp3 (audio file)
4. .mp4 (video file)
5. .exe (executable file)
6. .dat (binary data file)

B.E- First Year, Sem-2 Page: 20


Programming for Problem Solving Using Python MVSREC

3. Modes of files
Mode of a file specifies the type of operation on the file such as file opened for writing or
reading etc.
Python supports twelve modes of files. Six modes are for text files and six modes are for
binary files which are described below.

sl.no File mode Description

1 “w” Text file opened in write mode. Creates a new file if file not
found

2 “r” Text file opened in read mode. Raises FileNotFoundError if


file not found

3 “a” Text file opened in append mode. Creates a new file if file
not found

4 “w+” Text file opened in both write/read mode. Creates a new file
if file not found

5 “r+” Text file opened in write/read mode. Raises


FileNotFoundError if file not found

6 “a+” Text file opened in read/append mode. Creates a new file if


file not found

7 “wb” Binary file opened in write mode. Creates a new file if file
not found

8 “rb” Binary file opened in read mode. Raises FileNotFoundError


if file not found

9 “ab” Binary file opened in append mode. Creates a new file if file
not found

10 “wb+” Binary file opened in both write/read mode. Creates a new


file if file not found

11 “rb+” Binary file opened in write/read mode. Raises


FileNotFoundError if file not found

12 “ab+” Binary file opened in read/append mode. Creates a new file


if file not found
Note: By default, the file will be opened in “read” mode if mode is not specified.
Difference between “write” mode and “append” mode:
“Write” mode overrides the previous data inside the text/binary file

B.E- First Year, Sem-2 Page: 21


Programming for Problem Solving Using Python MVSREC

“Append” mode preserves the previous data and also adds new data to the end of
the text/binary file.
Both modes will create a new file if the file is not found.
4. File operations
In python, a file is used to perform following operations:
a. Creating a new file
b. Writing data to the file
c. Reading the data from an existing file
d. Appending the data to the file
e. Closing the file
Creating a new file: We can create a new file at a specified location in the hard
disk drive. Python has built-in function “open()” to create a new file.
To create a new file, file mode should be either “write” mode or “append” mode.
Syntax to create a new file:
fileVariable=open(filename,filemode)
Example to create a new file:
file=open(“demo.txt”,”w”)
We can create a new file using the “with” keyword. Below is the syntax.
with open(filename,filemode) as fileVariable:
#file related statements
Example:
with open(“demo.txt”,w”) as file:
print(“file created”)
Note: Files created using “with” keyword will be closed automatically without calling
close() function. If “with” is not used then the file should be opened and closed explicitly by
calling close() function.
Writing data to the file: After creating a new file, we can write data to the file using the
built-in functions write() and writelines().
write() function writes a string of data to file whereas writelines() function writes list of strings to
the file.
Syntax:
with open(filename,filemode) as fileVariable:
#fileVariable.write(stringdata)
# fileVariable.writeline(listdata)
Example-1:
with open(“demo.txt”,w”) as file:
print(“file created”)
data=”hello world”
file.write(data)
Example-2:

B.E- First Year, Sem-2 Page: 22


Programming for Problem Solving Using Python MVSREC

Output Data inside file demo.txt

Reading the data from existing file:


We can read the data that already exists in the existing file. Python supports three built-in
functions to read data from the file.
I. read() function: this function reads the entire data from the file or specified number of
characters/bytes from the file and returns the read data as a string.
Syntax :
result=fileVariable.read()
Or
result=fileVariable.read(integer)
II. readline() : This function reads a line of data from the file and returns the read data as
a string.
Syntax :
result=fileVariable.readline()
III. readlines(): This function reads all lines of data from the file and returns the list of
lines as result.
Syntax :
result=fileVariable.readlines()
Examples
Assume the data in the “demo.txt” is

B.E- First Year, Sem-2 Page: 23


Programming for Problem Solving Using Python MVSREC

demo.txt

Example-1

Output-1

Example-2

Output-2

Example-3

Output-3

Example-4

Output-4

B.E- First Year, Sem-2 Page: 24


Programming for Problem Solving Using Python MVSREC

Appending the data to the file:


To append the new data, we open the file in append mode. Append mode will preserve
the old data and new data will be added from the last character of the previous existing data.
We use the same write() function to append the data, but the file mode is “a”.
Syntax:
with open(filename,”a”) as file:
file.write(stringdata)
Example:

demo.txt (before
append)

Example

Output

demo.txt (after
append)

Closing the file:


Once a file is opened, it should be closed for future access. Python has built-in function
close() to close the file.
→ We cannot access fileVariable after calling close as it no longer refers to any file.
Syntax:
fileVariable=open(filename,filemode):
#file statements
fileVariable.close()

B.E- First Year, Sem-2 Page: 25


Programming for Problem Solving Using Python MVSREC

Note: if file is opened using “with” keyword, we no need to call close() as file will be closed
automatically.
Example:
file=open(“demo.txt”,”r”)
print(“file opened”)
file.close()
print(“file closed”)
5. File attributes
In python a file is an object that has built-in methods and attributes.
File attributes specify the file information such as file name, file mode, file size, file closed or
not etc.
Below are a few frequently used file attributes.

Attribute purpose example


name

name Returns the name of the file

mode Returns the mode of the file

closed Returns true or false. Returns False if the file is


opened. Returns True if the file is closed.

6. File positions
When a file containing some data is opened, a file cursor is internally maintained by the file
object. File cursor is used to indicate the current position of the file when data is written or read.
we can perform a few below special operations on file. We can
→ fetch the current position of the file
→ set the position of a file

Fetching the current position of file:


In Python, file object has a built-in method “tell()” to fetch the current position of the file.
tell() function returns the position of a file as a number. Position should be taken from top left
towards right inside the file.
Syntax:
with open(filename,filemode) as fileVariable:
print(fileVariable.tell())
Example:

B.E- First Year, Sem-2 Page: 26


Programming for Problem Solving Using Python MVSREC

The below example returns the current position of file after reading 10 characters from
file and reading total data from the file.

Output

Setting the position of the file:


In Python, file object has a built-in method “seek()” to set the position of the file.
After setting the file position, file content will be read from that position.
Syntax of seek() function:
fileVariable.seek(offsetValue,offsetPosition)
offsetValue is a positive integer that indicates the number of characters to be skipped from the
given offsetPosition.
offsetPosition has below three possible values to set the position of the file.

value Position of the file

0 Sets to the beginning of the file

1 Sets to the current position of the file

2 Sets to the end of the file


For example, f.seek(3,1) means the file will be read from the current position of the file by
skipping 3 characters from the current position.
f.seek(-3,2) means the file will be read from the end of the file by moving the file cursor back to
3 characters from the end towards right to left.

B.E- First Year, Sem-2 Page: 27


Programming for Problem Solving Using Python MVSREC

Example program:

Output

7. File paths
After creating a file using the open() function, we can access the path of the file.
Path of the file can be of two types:
i) Absolute path: the complete path of the file from the root directory to the file location.
ii) Relative path: it is a portion of the absolute path of the file which is not complete. It
specifies the path from the parent directory to the file.
As a user we can decide from which parent directory, the file path should be fetched.
File objects don’t have built-in methods to get the path of the file.
To change the name of a file, we need to import the “os” module and call abspath() function and
relapth() function to fetch absolute path and relative path respectively.
Syntax:
import os
with open(filename,filemode) a fileVariable:
os.apth.abspath(filename)
ps.relpath(filename,pathtoExclude)
Example:
Below example prints both absolute path and relative path of the file “demo.txt”

B.E- First Year, Sem-2 Page: 28


Programming for Problem Solving Using Python MVSREC

Assume location of “demo.txt” is “D:\python notes\files\file paths\demo.txt '' in windows


operating system. Absolute path fetches complete path of the file. The below code fetches
relative path from parent directory “files”. So we must mention the path which should be
excluded to fetch as a parameter in the relpath() function.
Observe below code: relpath(file.name,”d:\\python notes”) which means that the file path should
be fetched from the sub directories of “python notes”

Output

8. Renaming and deleting a file


Renaming a file: Renaming means changing the name of the existing file.
File objects don’t have built-in methods to rename a file.
To change the name of a file, we need to import the “os” module and call rename() function.
Syntax:
import os
os.path.rename(oldfilename,newfilename)
Deleting a file:
File objects don’t have built-in methods to delete a file.
To change the name of a file, we need to import the “os” module and call remove() function.
Syntax:
import os
os.path.remove(filename)
Below example shows renaming and deleting a file

B.E- First Year, Sem-2 Page: 29


Programming for Problem Solving Using Python MVSREC

Output

Example Programs
1. Program to copy the contents from one file to another file
Solution:

2. Program to copy data from one file to another file and inserts line numbers in the
copied file
Solution:

B.E- First Year, Sem-2 Page: 30


Programming for Problem Solving Using Python MVSREC

3. Program to read a file and display the contents in upper case


Solution:

B.E- First Year, Sem-2 Page: 31


Programming for Problem Solving Using Python MVSREC

4. Program to find number of words,lines and characters in a file

B.E- First Year, Sem-2 Page: 32


Programming for Problem Solving Using Python MVSREC

PART- III: GUI PROGRAMMING

1. Introduction to GUI
● What is GUI? Graphical User Interface (GUI) is one of the most usable user interfaces
for interacting with the python application in any operating system like windows, linux,
macos etc.
● Using GUI, users interact with applications through clickable graphical components like
buttons, menus, checkbox, radiobutton, entry fields, dropdown lists etc.
● It provides a user-friendly interface that users feel comfortable to interact with programs.
● All inputs and outputs to the application happens through gui windows.
2. Difference between terminal based applications and GUI applications

Terminal Based application GUI based application

User interacts with the application User interacts with the application using
in the form plain text graphical components like clickable
buttons,icons,images etc.

Not so user friendly to run an Much user friendly to run an application


application

Interface is through keyboard Interface is through keyboard and mouse


between user and application between user and application

Uses only text as medium to read Uses multimedia like text,


inputs, produce outputs and images,audio,video, graphical components
compute any other information to read inputs,produce outputs and get any
other information.

Speed of execution is fast Speed of execution is slow

Navigation is not easy in the Navigation is easy between multiple


middle of execution applications

Low memory usage and less High memory usage and high flexible user
flexible user interface interface

User needs to remember User no need to remember commands to


commands to operate an operate application
application

Operable by professional users Operable by normal users also who know


computer basics.

B.E- First Year, Sem-2 Page: 33


Programming for Problem Solving Using Python MVSREC

3. Creating a GUI window using Tkinter module


➔ In python, there is a standard built-in module “Tkinter” to design and
develop gui programs.
➔ Other than “Tkinter”, there are other alternatives like “kivy”, “PyQt”,
“wxPython” for building Gui programs.
➔ Here, we implement gui programs using “Tkinter”. It has few important
features:
◆ Used to build desktop applications with comfortable code
◆ Easy to learn and implement
◆ Supports bunch of built-in graphical components to use
◆ Portable across multiple operating systems like windows,linux,
mac etc
➔ Note: Tkinter is pronounced as “T-kay-inter”
➔ For any gui program, first a root window or main window must be created.
For this , a Tkinter object is initialized named as “Tk()”
Below are the steps to create and run GUI window using Tkinter
a. Import Tkinter module using below line
From tkinter import *
b. Create a Tkinter object
window=Tk()
c. Configure Tkinter window using geometry methods (Optional)
d. Create and Add Tkinter’s GUI widgets like buttons, label, entry etc.
(Optional)
e. Apply event handling code to GUI widgets (Optional)
f. Run the tkinter GUI window
window.mainloop()
Example to create a simple GUI window

Program Output

B.E- First Year, Sem-2 Page: 34


Programming for Problem Solving Using Python MVSREC

4. Tkinter widgets
Python allows many built-in graphical components called Widgets to be inserted inside
Tkinter main window and allows configuring them. Few of them are described below.
a. Label
It is a tkinter gui widget to display static text on the tkinter window.
Label is not an interactive component, it is just used to guide the user to
interact with the application.
Syntax
variable=Label(text=”Text to display”,[configuration
parameters])
Example
l1=Label(text=”Enter name:”)
b. Entry
It is a tkinter gui widget that allows you to enter a single-line input text.
The text entered by default will be stored as a String. Later it should be
type casted to required type explicitly.
Syntax:

variable=Entry(width=value,textvariable=variableName,[confi
guration parameters])
Example-1
e1=Entry(width=10,textvariable=v1)
#This statement creates an Entry component of width 10pixels. Input will
be stored in the v1 variable.
Example-2
e1=Entry(width=10,textvariable=v1,show=’*’)
#This statement creates an Entry component of width 10pixels. Input will
be stored in the v1 variable and entered data will be masked with “*”.
Used to enter passwords.
Structure :

c. Button
It is a tkinter gui widget that represents a clickable item in the application.
Button requires actions to be invoked upon click. So it takes a special
parameter “command” to map the clicks to the corresponding action to
invoke.
Syntax:
variable = Button(text=”Text to display”,
command=functionName,[configuration parameters])

B.E- First Year, Sem-2 Page: 35


Programming for Problem Solving Using Python MVSREC

Example:
b1=Button(text=”click me”)
Structure:

d. Checkbutton
A checkbox is a widget that allows you to check and uncheck.
A checkbox can hold a value and invoke a callback when it’s checked or
unchecked.
Typically, we use a checkbox when we want to collect data from multiple
selections.
We need to import the “ttk” sub-module from tkinter to use Checkbutton.
Syntax:
variable=Checkbox(text=”text to display”,
variable=variableName)
text → specifies the text to display on screen
tariable → stores two possible values in the given variable. When the
checkbox is selected the value assigned will be 1,if it is not selected then
value will be 0.
Example to create 3 checkboxes to check languages known:
cb1=Checkbox(text=’C’,variable=v1)
cb2=Checkbox(text=’python’,variable=v2)
cb3=Checkbox(text=’java’,variable=v3)
Structure:

e. Radiobutton
It is a gui widget that allows you to select only one option from the given
multiple choices.
All radio buttons must be grouped with a common variable such that it
stores only one value which is selected.
Syntax
rb1=Radiobutton(text=”text to display”,
variable=variableName,value=numericvalue)
Example
rb1=Radiobutton(text='Male',variable=v5,value=1)
rb2=Radiobutton(text='Female',variable=v5,value=2)
Observe that two radio buttons rb1,rb2 has same variable name v5 which
is grouped together. If rb1 selected, v5 value is 1 else v5 value is 2
Structure:

B.E- First Year, Sem-2 Page: 36


Programming for Problem Solving Using Python MVSREC

f. Combobox
It is a gui widget that allows you to generate a drop down list of items.
User has to select one item from the list of items.
We need to import the “ttk” sub-module from tkinter to use Combobox.
Syntax:
cbb=ttk.Combobox(textvariable=variable)
cbb['values']=(tuple of items)
cbb['state']='readonly'
Note:
cbb[‘values’] → used to set the items to be displayed for combobox
cbb[‘read-only’] → set the combobox items to be immutable.
Example:
cbb=ttk.Combobox(textvariable=v4)
cbb['values']=('CSE','ECE','EEE','IT','CIVIL','MECH')
cbb['state']='readonly'
Structure :

5. Tkinter geometry management


● It is used to organize or arrange the widget elements on the parent Tk
window.
● Also used to apply functionality on parent window for setting its
dimensions
● Tk object uses the below geometry management methods to organize the
widgets in main window
○ pack() → arrange every widget as block element i.e that comes on
next row by default
○ grid(column,row) → arrange every widget in grid(table-like
structure) with specified row and column
○ place(x,y) → allow widget to place in a Tk window with given x,y
positions
● The following methods are used to configure the dimensions, title and
window adjustment of the Tk window.

B.E- First Year, Sem-2 Page: 37


Programming for Problem Solving Using Python MVSREC

○ title(stringName) → sets the title for Tk window. “Tk” is the


default title.
○ geometry(StringDimension) → adjust the width and height of the
Tk window as per given StringDimension.
For example, ‘500X200’ is the stringDimension, then width =500
and height=200 for the Tk window.
○ resizable(boolean,boolean) → enable and disable the adjustment
of the Tk window.
For example, resizable(False,False) means that the Tk window
cannot be resized as widthwise or height wise.
Note: All these geometry methods should be called on Tk window object and Widget
objects.
Program:
Below program demonstrates on calling geometry methods to configure Tk window and attach
widgets to Tk using widget methods.

B.E- First Year, Sem-2 Page: 38


Programming for Problem Solving Using Python MVSREC

Output

6. Event driven programming


● What is an event?
An event is something that changes the state of a GUI widget.
● For example, clicking a button, selecting and deselecting Radiobutton or
Checkbutton, selecting an item from Combobox, clicking on Tk window
controls minimize,maximize,close, selecting a text in Entry etc.
● When a Gui component changes from its original state from the point of
execution, then we say an event occurred on that widget.
● What is an event driven program?
○ The process of assigning a function to an event of a widget is
called event binding or event driven program.
○ When the event occurs, the assigned function is invoked
automatically.
○ A gui widget is a physical component which is static without any
action.
○ A function is used to define some relevant logic or action.
○ So, the process of mapping the function to the gui widget when an
event occurs is called event driven programming.
● Observe the below example:
def compute():
print(“compute called”)
btn=Button(text=”click me”, command=compute)
● Here, the Button takes a parameter command which is used to assign the
function “compute” to the Button.
● Now, the Button is mapped with the compute() function, which means that
when a button is clicked, compute() will be triggered and execute its logic.
● Not all widgets use the “command” parameter to trigger the function.
There are some widgets which use bind() method to map events with a
widget.

B.E- First Year, Sem-2 Page: 39


Programming for Problem Solving Using Python MVSREC

● Syntax of bind() method:


widget.bind(event,handlerfunction,add=None)
● Example: When the mouse pointer moves over the Button, function
compute invokes.
def compute():
print(“compute called”)
btn=Button(text=”click me”)
btn.bind(‘<Enter>’,compute)

Overview of GUI with event driven:

7. Displaying notification dialog boxes


● A notification dialog box is a small window to display notifications when
some action has been done in the tk window.
● When developing a Tkinter application, we often want to notify users
about the events that occurred.
● For example, when users click the save button, you want to notify them
that the record has been saved successfully.
● If an error occurred, for example, entering a wrong input, you can notify
users of the error.
● When some spurious action is to be performed, you may want to show an
alert/warning.

B.E- First Year, Sem-2 Page: 40


Programming for Problem Solving Using Python MVSREC

● To cover all of these scenarios, you can use various functions from the
"tkinter.messagebox" module:
○ showinfo() – notify that an operation completed successfully.
○ showerror() – notify that an operation hasn’t completed due to an
error.
○ showwarrning() – notify that an operation completed but
something didn’t behave as expected.
Syntax:
All of these functions accept two arguments:
showinfo(title,message)
showerror(title,message)
showwarning(title,message)
Example:
def compute():
messagebox.showinfo(“Notify”,”button
clicked”)
btn=Button(text=”click me”)
btn.bind(‘<Enter>’,compute)
Program:
Below program creates a gui window with a label, entry and button. An alert notification will be
displayed when the button is clicked.

B.E- First Year, Sem-2 Page: 41


Programming for Problem Solving Using Python MVSREC

Output -1

Output -2

B.E- First Year, Sem-2 Page: 42


Programming for Problem Solving Using Python MVSREC

Output -3

8. Widget Configuration parameters


Most of the widgets have some common parameters to apply some settings on
their physical structure. Few of the parameters are:
a. fg → sets foreground color of a widget
b. bg → sets background color of a widget
c. bd → sets the border width of a widget
d. font → sets the font and font size for a widget
Example:

9. Example programs
a. Create a GUI to perform addition of two numbers
Program:

B.E- First Year, Sem-2 Page: 43


Programming for Problem Solving Using Python MVSREC

B.E- First Year, Sem-2 Page: 44


Programming for Problem Solving Using Python MVSREC

Output

b. Creating a Login application


Below program is to build a gui for entering some username and password and
authenticate it.If user enters username as “abcd” and password as “1234” then application
display a dialog box saying “login success” else displays “invalid credentials”
Program:

B.E- First Year, Sem-2 Page: 45


Programming for Problem Solving Using Python MVSREC

B.E- First Year, Sem-2 Page: 46


Programming for Problem Solving Using Python MVSREC

Output -1

Output -2

c. Building a registration form


Below program build a gui for student registration form that collect data from user.
Program uses gui widgets like Button,Entry,Label, RadioButton,Checkbutton to collect
data. Once the button “save” is clicked, the data will stored in a file and confirmation
dialog box will be displayed saying “data saved successfully”

Program:

#GUI-Student Registration Form


from tkinter import *
from tkinter import messagebox
from tkinter import ttk
tk=Tk()
tk.title("Registration Form")
tk.resizable(0,0)
tk.geometry('600x600')

B.E- First Year, Sem-2 Page: 47


Programming for Problem Solving Using Python MVSREC

v1=StringVar()
v2=StringVar()
v3=StringVar()
v4=StringVar()
v5=IntVar()
v6=IntVar();v7=IntVar();v8=IntVar()
def clear():
v1.set("")
v2.set("")
v3.set("")
v4.set("")
v5.set(0)
v6.set(0)
v7.set(0)
v8.set(0)
def save():
a=v6.get();b=v7.get();c=v8.get();d=v5.get()
cbdata="";rbdata=0
if d==1:
rbdata='Male'
else:
rbdata='Female'
if a==0 and b==0 and c==0:
cbdata="None"
elif a==1 and b==1 and c==1:
cbdata="C,Python,Java"
elif a==0 and b==0 and c!=0:
cbdata="Java"
elif a==0 and b!=0 and c==0:
cbdata="Python"
elif a!=0 and b==0 and c==0:
cbdata="C"
elif a!=0 and b!=0 and c==0:
cbdata="C,Python"
elif a!=0 and b==0 and c!=0:
cbdata="C,Java"
elif a==0 and b!=0 and c!=0:
cbdata="Python,Java"

with open('save.txt','w') as f:
f.write("Student Details are:\n==========\n")
f.write("Name="+v1.get())
f.write("\nRoll number="+v2.get())
f.write("\nBranch="+v4.get())
f.write("\nGender="+rbdata)
f.write("\nEmail="+v3.get())

B.E- First Year, Sem-2 Page: 48


Programming for Problem Solving Using Python MVSREC

f.write("\nLanguages Known="+cbdata)
messagebox.showinfo("Message","Student details saved
successfully...!")
l1=Label(text='Enter student name:')
l2=Label(text='Enter Roll number:')
l3=Label(text='Select branch:')
l4=Label(text='Select Gender:')
l5=Label(text='Enter Email:')
l6=Label(text='Prog. languages Known:')
l7=Label(text='Enter Address:')
e1=Entry(width=20,textvariable=v1)
e2=Entry(width=20,textvariable=v2)
e3=Entry(width=20,textvariable=v3)
e4=Text(width=20,height=3)
rb1=Radiobutton(text='Male',variable=v5,value=1)
rb2=Radiobutton(text='Female',variable=v5,value=2)
cb1=Checkbutton(text='C',variable=v6)
cb2=Checkbutton(text='Python',variable=v7)
cb3=Checkbutton(text='Java',variable=v8)
cbb=ttk.Combobox(textvariable=v4)
cbb['values']=('CSE','ECE','EEE','IT','CIVIL','MECH')
cbb['state']='readonly'
b1=Button(text='Save',command=save)
b2=Button(text='Clear',command=clear)
b3=Button(text='Quit',command=tk.destroy)
l1.grid(row=3,column=5)
e1.grid(row=3,column=7)
l2.grid(row=5,column=5)
e2.grid(row=5,column=7)
l3.grid(row=7,column=5)
cbb.grid(row=7,column=7)
l4.grid(row=9,column=5)
rb1.grid(row=9,column=7)
rb2.grid(row=9,column=10)
l5.grid(row=11,column=5)
e3.grid(row=11,column=7)
l6.grid(row=13,column=5)
cb1.grid(row=13,column=7)
cb2.grid(row=13,column=9)
cb3.grid(row=13,column=11)
l7.grid(row=15,column=5)
e4.grid(row=15,column=7)
b1.grid(row=17,column=5)
b2.grid(row=17,column=8)
b3.grid(row=17,column=11)
tk.mainloop()

B.E- First Year, Sem-2 Page: 49


Programming for Problem Solving Using Python MVSREC

Output

saved file

B.E- First Year, Sem-2 Page: 50

You might also like