Python Programming Lab
Python Programming Lab
LAB MANUAL
Lab Incharges :
3. String Operations
4. Largest of n Numbers
5. Matrix Multiplication
8. Operator Overloading
9. File Handling
15. Display an Image and its Transformation using Tkinter and OpenCV-Python
Additional Exercises
1. Factorial of an Integer
***
1. Generation of Prime Numbers
Aim: To generate prime numbers within an interval using for and while statements.
Algorithm:
A prime number is an integer number greater than 1 whose only factors are 1 and itself. The
first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29.
To check whether a given number (num) is a prime number, first divide it by 2. If the result is
an integer number (i.e., num is divisible by 2 or remainder of num/2 is zero or num % 2 is 0)
then num is not a prime number. If not, try to divide it by prime numbers 3, 5, 7, 11, … , up to
num-1 or divide it by 3, 4, 5, …. , up to num-1. If num is not divisible up to num-1 then num is a
prime number.
# To display all the prime numbers within a given interval [Lower, Upper]
Result:
# Python program to display all the prime numbers within a given interval [Lower, Upper] using
while statement
num=lower
while(num<=upper):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
num=num+1
Result:
Enter Lower Limit: 50
Enter Upper Limit: 100
Prime numbers between 50 and 100 are:
53
59
61
67
71
73
79
83
89
97
>>>
2. Solving Quadratic Equation
Aim: To find the roots of a quadratic equation given the coefficients a, b and c.
Algorithm:
Examples: x2 + 5x + 6 = 0, 4x2 + 5x + 8 = 0.
The values of x that satisfy the equation are called solutions or roots of the equation. A
quadratic equation has always two roots. It can be found by computing d = b2 - 4ac. The value of
d is zero or +ve or -ve.
i) If d = 0 then then the roots are real and equal. They are root1 = -b/(2a) and root2 = -b/(2a).
ii) If d > 0 then the roots are real and different. They are root1=-b+√d/(2a) and root2=-b-√d/(2a).
iii) If d < 0 then the roots are complex or imaginary. Roots are of the form p + iq and p - iq,
where p is the real part of the root and q is the imaginary part of the root. The real part of the root
is p = -b/(2a) and the imaginary part is q = √-d/(2a).
Coding:
import math,cmath
d = (b**2) - (4*a*c)
if d==0:
sol1 = -b/(2*a)
sol2 = -b/(2*a)
print("Roots are real and equal")
elif d>0:
sol1 = (-b-math.sqrt(d))/(2*a)
sol2 = (-b+math.sqrt(d))/(2*a)
print("Roots are real and different")
elif d<0:
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print("Roots are imaginary")
Result:
Enter a, b and c: 1 4 4
Roots are real and equal
-2.0 and -2.0
>>>
Enter a, b and c: 1 5 6
Roots are real and different
-3.0 and -2.0
>>>
Enter a, b and c: 1 2 3
Roots are imaginary
(-1-1.4142135623730951j) and (-1+1.4142135623730951j)
>>>
3. String Operations
Aim: To perform the string operations using user defined functions.
Algorithm:
A string is a data type used in programming, such as an integer and floating point numbers, but
it is used to represent text rather than numbers. It is comprised of a set of characters. Character
array is used to store a string.
Examples: “Annamalai”, “2345”
The main operations on string are: length of a string (counting number of characters in the
string), reversing a string, concatenating two strings together and comparing two strings. In
Python, the arithmetic operator ‘+’ is used for string concatenation and the relational operators
‘<’, ‘<=’, ‘>’, ‘>=’ ‘==” are used for string comparison. In Python, a function is defined using
the def keyword.
Coding:
# String Operations: String Length, String Reverse, String Concatenation and String Comparison
def strlen(str):
counter = 0
while str[counter:]:
counter += 1
return counter
def strrev(str):
rstr=""
l=strlen(str)
while l>0:
rstr = rstr + str[l-1]
l=l-1
return rstr
def strcat(st1,st2):
return(st1+st2)
def strcmp(st1,st2):
if(st1==st2):
print(st1 + " and " + st2 + " are same")
elif (st1>st2):
print(st1 + " comes after " + st2 +" in the Dictionary")
else:
print(st1 + " comes before " + st2 +" in the Dictionary")
print("String Functions:\n 1. String Length \n 2. String Reverse \n 3. String
Concatenation\n 4. String Comparison\n")
n=int(input("Enter your Choice: "))
if(n==1):
str = input("Enter a String: ")
print("Length of the string is:",strlen(str))
elif (n==2):
str = input("Enter a String: ")
print("Reversed String is:", strrev(str))
elif (n==3):
str1 = input("Enter the first String: ")
str2 = input("Enter the second String: ")
print("Concatenated string is:", strcat(str1,str2))
elif (n==4):
str1 = input("Enter the first String: ")
str2 = input("Enter the second String: ")
strcmp(str1,str2)
else:
print("Invalid Choice")
Result:
String Functions:
1. String Length
2. String Reverse
3. String Concatenation
4. String Comparison
>>>
String Functions:
1. String Length
2. String Reverse
3. String Concatenation
4. String Comparison
String Functions:
1. String Length
2. String Reverse
3. String Concatenation
4. String Comparison
Algorithm:
A list is a data structure in Python. List contains ordered sequence of elements and it can be
changeable. Python list is like an array in other languages. List need not have homogeneous
(same data type) items or elements which makes it a most powerful data structure in Python. A
single list may contain data types like integers, floating numbers, strings etc.,
Creating List: Initially, an empty list is created. The n elements are added to the list one by one
using append() built-in function.
Function: In Python a function is defined using the def keyword. To find largest of n given
numbers, the first number is assumed to be the largest. The second number is compared with the
largest. If the second number is greater than the largest then the second number is made as the
current largest number. This process is repeated for all other remaining numbers in the list to find
the largest number. In Python, built-in function max() can also be used to find largest of n
numbers (i.e., largest=max(lst))
Coding:
def lar(lst,n):
l=lst[0]
for i in range(1,n):
if (lst[i]>l):
l=lst[i]
return l
lst=[]
n=int(input("Enter total number of elements: "))
print("Enter the elements one by one: ")
for i in range(n):
num=float(input())
lst.append(num)
print("The given elements are:")
print(lst)
print("Largest number is",lar(lst,n))
Result:
Algorithm:
An array is a data structure and it is used to store same type (data type) of elements/values. In
python, list can contain elements of different data types.
Creating List: Initially, an empty list is created. The Matrix A elements (m x n elements) are
added to the list one by one using append() built-in function.
Creating Array: The storage requirement for an array need to specified. The Matrix B elements
( n x p elements) are read one by one and stored into the array.
for i = 0 to m-1
for j = 0 to p-1
begin
c[i][j] = 0
for k = 0 to n-1
begin
c[i][j] = c[i][j] + a[i][k] * b [k][j]
end
end
Coding:
def matmul(a,b,m,n,p):
c=[[0 for j in range (0,p)] for i in range (0,m)]
for i in range(m):
for j in range(p):
c[i][j]=0
for k in range(n):
c[i][j]=c[i][j]+a[i][k]*b[k][j]
return c
a=[]
print("Enter the elements of the first matrix (row-order): ")
for i in range(m):
r=[]
for j in range(n):
r.append(int(input()))
a.append(r)
print("Matrix A is:")
print(a)
print("Matrix B is:")
print(b)
print ("Resultant matrix is:")
print(matmul(a,b,m,n,p))
Result:
Enter number of rows of the first matrix: 2
Enter number of columns of the first matrix: 2
Enter number of columns of the second matrix: 2
Enter the elements of the first matrix (row-order):
1
2
3
4
Enter the elements of the second matrix (row-order):
1
1
1
1
Matrix A is:
[[1, 2], [3, 4]]
Matrix B is:
[[1, 1], [1, 1]]
Resultant matrix is:
[[3, 3], [7, 7]]
>>>
6. Class and Objects
Aim: To define a class with constructor and create objects.
An object is an instance of a class. When a class is defined, no memory is allocated but when it
is instantiated (i.e. an object is created) then the memory is allocated.
The __init__() function in the class is executed automatically every time the class is being
used to create a new object. It is called as a constructor in object oriented terminology. This
function is used to initialize the data members of the class.
In most of the object-oriented programming (OOP) languages access specifiers are used to
limit the access to the variables and functions of a class. Most of the OOP languages use three
types of access specifiers, they are: private, public and protected. In Python, all the variables
and member functions of a class are public by default. Adding a prefix __ (double underscore)
to the member variable or function makes them to be private.
Coding:
# To find the Euclidean distance between two pints in a three dimensional space using
# class and objects.
import math
class point():
def __init__(self,a,b,c):
self.x=a
self.y=b
self.z=c
def distancefromorigin(self):
return ((self.x ** 2) + (self.y ** 2) +(self.z ** 2)) ** 0.5
p1 = point(x1,y1,z1)
p2 = point(x2,y2,z2)
print('Distance from origin to P1:', p1.distancefromorigin())
print('Distance from origin to P2:', p2.distancefromorigin())
print('Distance from P1 to P2:',p1.distance(p2))
Result:
Enter the coordinates of a first point P1(x1,y1,z1): 1 2 3
123
Enter the coordinates of a second point P2(x2,y2,z2): 2 3 4
234
Distance from origin to P1: 3.7416573867739413
Distance from origin to P2: 5.385164807134504
Distance from P1 to P2: 1.7320508075688772
>>>
7. Single and Multiple Inheritance
Aim: To define a new class from one or more existing classes.
Inheritance:
Inheritance is a mechanism in which one class (derived class) acquires the property of
another class (base class). With inheritance, we can reuse the variables and methods of the
existing class. The existing class is called base class and the new class is called derived class.
Hence, inheritance facilitates reusability and is an important concept of object oriented
programming. Types of inheritance are: single inheritance, multiple inheritance, multi-level
inheritance, hierarchical inheritance and hybrid inheritance.
Single inheritance enables a derived class to use the variables and functions defined in an existing
class. In multiple inheritance, derived class inherits the characteristics and features from more than one
existing classes.
In python, syntax for defining single inheritance is class z(x), where x is the name of the base class and
z is the name of the derived class. Similarly, multiple inheritance is defined using the syntax class z(x, y),
where x and y are the names of base classes and z is the name of the derived class.
Coding:
class person:
self.name = n
self.age = a
class employee(person):
person.__init__(self,n,a)
self.designation=d
self.salary=s
def show(self):
class student:
self.studentId = id
self.roomno=rno
# resident is a class derived from person and student using multiple inheritance
person.__init__(self, n, a)
student.__init__(self, id,rno)
def show(self):
print("Resident Details:")
print(" Name:", self.name,"\n Age: ",self.age, "\n Id:" ,self.studentId,"\n Room no.:",self.roomno)
e1 =employee("Arun",35,"Data analyst",50000)
e1.show()
r1.show()
Result:
Employee Details:
Name: Arun
Age: 35
Salary: 50000
Resident Details:
Name: John
Age: 30
Id: 201900025
>>>
8. Operator Overloading
Aim: To overload the binary operators to perform operations on objects.
Operator Overloading:
Operator overloading allow us to redefine the way operator works for user-defined types such as
objects. It cannot be used for built-in types such as int, float, char etc., For example, '+' operator can be
overloaded to perform addition of two objects of distance class.
Python provides some special function or magic function that is automatically invoked when it is
associated with that particular operator. For example, when we use + operator on objects, the magic
method __add__() is automatically invoked in which the meaning/operation for + operator is defined for
user defined objects.
Coding:
class distance:
self.feet=f
self.inches=i
def __gt__(self,d):
if(self.feet>d.feet):
return(True)
return(True)
else:
return(False)
# overloading of binary operator + to add two distances
i=self.inches + d.inches
f=self.feet + d.feet
if(i>=12):
i=i-12
f=f+1
return distance(f,i)
def show(self):
a,b =[int(a),int(b)]
c,d =[int(c),int(d)]
d1 = distance(a,b)
d2 = distance(c,d)
if(d1>d2):
else:
d3.show()
Result:
84
69
Feet= 15 Inches= 1
>>>
9. File Handling
Aim: To perform file operations such as open read, write and close on text and numeric data
files.
File Handling:
A file is a collection of data stored in one unit, identified by a filename. It can be a text
document, picture/image, audio, audio-video or other collection of data. The common
format/extensions for text documents are .doc, .docx (Microsoft word documents), .odt
(LibreOffice open document text), .pdf (Adobe portable document format) , rtf (Microsoft rich
text format), .tex (LaTeX text), .txt (Microsoft Notepad text). The image file formats are: .jpg,
.tiff, .gif, .png, bmp. The commonly used audio formats are: .wav and .mp3. The audio-video
format includes .avi, .mp4, .mkv, .mov, .flv, .wmv etc.,
Python supports file handling and allow users to handle files i.e., to read and write files, along
with many other file handling options, to operate on files. Python file functions open() and
close() are used for opening and closing a file. The read() and write() functions are used for
reading and writing text (or numeric or binary data) from/to the file, respectively. File opening
modes in Python are: r (read), w (write), a (append), rb (reading binary data), wb(writing binary
data).
# File copy – content of a text file (input.txt) is copied to another text file (output.txt)
infile=open("/media/yughu/D/input.txt","r")
outfile=open("/media/yughu/D/output.txt","w")
lines = chars = 0
lines += 1
chars += len(line)
outfile.write(line)
infile.close()
outfile.close()
Result:
# sum of all the numbers in the input file (input.dat) is computed and
# it is written to the output file (output.dat)
infile=open("/media/yughu/D/input.dat","r")
outfile=open("/media/yughu/D/output.dat","w")
sum=0
s = infile.read()
numbers = [int(x) for x in s.split()]
print("The numbers are:")
print(numbers)
sum=str(sum)
outfile.write("Sum is ")
outfile.write(sum)
infile.close()
outfile.close()
Result:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
10. Exception Handling
Aim: To understand and handle different types of exceptions that occurs at runtime in the
program and also the method of raising an exception.
Exception Handling:
Exceptions are run-time anomalies or abnormal conditions that a program encounters during its
execution such as division by zero (ZeroDivisionError), opening a file for reading that does not
exist (IOError), indentation is not specified properly (IndentationError) etc., In general, an
exception breaks the normal flow of execution. Exception handling enables a program to deal
with exceptions and continue its normal execution.
A try statement in Python can have more than one except clause to handle different exceptions.
The statement can also have an optional else and/or finally statement. The try-except syntax is:
try:
<body>
except <ExceptionType1>:
<handler1>
...
...
except <ExceptionTypeN>:
<handlerN>
except:
<handlerExcept>
else:
<process_else>
finally:
<process_finally>
The multiple excepts are similar to elifs in python. When an exception occurs, it is checked to
match an exception in an except clause after the try clause one by one (sequentially). If a match
is found, the handler for the matching case is executed and the rest of the except clauses are
skipped. Note that the <ExceptionType> in the last except clause may be omitted. If the
exception does not match any of the exception types before the last except clause, the
<handlerExcept> for the last except clause is executed.
A try statement may have an optional else clause, which is executed if no exception is raised in
the try body.
A try statement may have an optional finally clause, which is intended to define cleanup
actions that must be performed under all circumstances.
Coding:
# Hadling exceptions that occurs at runtime such as division by zero, syntax error and
try:
number1, number2 = eval(input("Enter two numbers separated by a comma: "))
result = number1 / number2
print("Result is", result)
if(number1==0):
raise RuntimeError()
except ZeroDivisionError:
print("Division by Zero")
except SyntaxError:
print("A comma may be Missing in the Input")
except RuntimeError:
print("May be Meaningless")
except:
print("Something Wrong in the Input")
else:
print("No Exceptions")
finally:
print("Finally Clause is Executed")
Result:
4,0
Division by Zero
>>>
56
>>>
0,9
Result is 0.0
May be Meaningless
>>>
>>>
Procedure:
UDP (User Datagram Protocol) is connection-less protocol which is suitable for applications
that require efficient communication that doesn't have to worry about packet loss.
To begin we will need to import the socket python module. Once we’ve got this we need to
declare the IP address that we will be trying to send our UDP messages to as well as the port number.
This port number is arbitrary but ensures that you aren’t using a socket that has already been taken.
Now that we've declared these few variables it’s time to create the socket through which we will be
sending our UDP message to the server. And finally, once we've constructed our new socket it's time
to write the code that will send our UDP messages.
Once we have coded our client we then need to move on to creating our server program which
will be continuously listening on our defined IP address and port number for any UDP messages. It is
essential that this server has to be run prior to the execution of the client python script or the client
script will fail. Once we’ve imported the socket module and declared our IP address and port number
we can create another socket which will look exactly like the socket we constructed in our client
program. And finally, once we've created our server socket, we need to write the code that will keep
our script continuously listening to this socket until its termination.
Client Coding: (client.py)
port = 5001 #assign random port value above 1024(up to 1024 ports are reserved)
data = obj.recv(1024).decode() # Receive the message from Server, packet size 1024
bytes
obj.send(message.encode())
import socket
host = "127.0.0.1"
port = 5001
server = socket.socket()
if str(data)== 'bye':
conn.close()
break
Result:
Window 1: (client.py)
Type message: Hai
Received from server: What is your favorite programming language?
Type message: Python
Received from server: OK. Number of Open Source Python Packages is available
in the Web.
Type message: Where it is available?
Received from server: Type "PyPI" in Google.
Type message: bye
Window 2: (server.py)
Connection from: ('127.0.0.1', 54363)
Received from Client: Hai
Type message: What is your favorite programming language?
Received from Client: Python
Type message: OK. Number of Open Source Python Packages is available in the
Web.
Received from Client: Where it is available?
Type message: Type "PyPI" in Google.
Received from Client: bye
Connection Terminated.
12. File Transfer using File Transfer Protocol
Aim: To send files from local host to server using FTP.
Procedure (Server): The server will host the network using the assigned host and port using
which the client will connect to the server. The server will act as the sender and the user will
have to input the filename of the file that he/she would like to transmit. The user must make sure
that the file that needs to be sent is in the same directory as the "server.py" program.
Procedure (Client): The client program will prompt the user to enter the host address of the
server while the port will already be assigned to the port variable. Once the client program has
connected to the server it will ask the user for a filename to be used for the file that will be
received from the server. Lastly the client program will receive the file and leave it in the same
directory under the same filename set as the user.
Server Coding:
import socket
s = socket.socket()
host = socket.gethostname() #Get localhost IP address
port = 8080 #assign port for session
s.bind((host,port)) #bind the socket to assigned host IP and port
s.listen(1) #put the socket into listening mode for 1 client
print(host)
print("Waiting for any incoming connection... ")
conn, addr = s.accept()
print(addr, "Has connected to the server")
import socket
s = socket.socket()
host = input(str("Please enter the host address of the sender: "))
port = 8080
s.connect((host,port))
print("Connected ... ")
Result:
Windows 1: (server.py)
Windows 2: (client.py)
Tkinter:
Python offers multiple options for developing GUI (Graphical User Interface). Out of all
the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to
the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to
create the GUI applications. Creating a GUI using Tkinter is an easy task.
4. Enter the main event loop to take action against each event triggered by the
user.
Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI
application. These controls are commonly called widgets. There are currently 15 types of widgets
in Tkinter.
In this coding, a GUI application is developed for computing loan payments. The code
consists of the following steps:
1. Design the user interface consisting of labels using Label( ), text entry boxes using Entry( ),
and a button using Button( ).
2. Process the event. When the button is clicked, the program invokes a callback functions, using
getMonthlyPayment( ) to obtain the user input for the interest rate, number of years, and loan
amount from the text entries. The monthly and total payments are computed using
computePayment( ) and displayed in the labels.
Coding:
class LoanCalculator:
def __init__(self):
self.annualInterestRateVar = StringVar()
self.numberOfYearsVar = StringVar()
self.loanAmountVar = StringVar()
self.monthlyPaymentVar = StringVar()
= E)
self.totalPaymentVar = StringVar()
def computePayment(self):
monthlyPayment =
self.getMonthlyPayment(float(self.loanAmountVar.get()),float(self.annualInterestRateVar.get()) /
1200,int(self.numberOfYearsVar.get()))
self.monthlyPaymentVar.set(format(monthlyPayment, "10.2f"))
self.totalPaymentVar.set(format(totalPayment, "10.2f"))
* 12))
return monthlyPayment;
Result:
The popup menu for arithmetic operations has been created using Tkinter and the results are verified.
15. Display an Image and its Transformation using Tkinter
and OpenCV-Python
Aim: To read and display an RGB color image and convert it into grayscale, negative and edge
images.
Image:
An image is defined as a two-dimensional function, f(x, y), where x and y are spatial
coordinates, and the amplitude of F at any pair of coordinates (x, y) is called the intensity of that
image at that point. When x, y, and amplitude values of F are finite, it is called a digital image. In
other words, an image can be defined by a two-dimensional array specifically arranged in rows
and columns. Digital Image is composed of a finite number of elements, each of which has a
particular value at a particular location. These elements are referred to as pixels or picture
elements.
Types of Images:
In this coding the select image button is used to select an image. The file dialog is used to
select the desired input image from the hard disk. After selecting an image four kinds of
operations are performed by clicking one button for each operation. The RGB button is used to
display the RGB color image, the gray button is used to display the gray image of the selected
image, the edge button is used to display the edge of the selected image, and the negative button
is used to show the negative of the selected image.
RGB Image:
An RGB image is an image in which each pixel is specified by three values, one each for
the red, blue, and green components of the pixel's color. RGB images are stored as an m-by-n-
by-3 data array that defines red, green, and blue color components for each individual pixel. The
color of each pixel is determined by the combination of the red, green, and blue intensities stored
in each color plane at the pixel's location. Graphics file formats store RGB images as 24-bit
images, where the red, green, and blue components are 8 bits each. This yields a potential of 16
million (224) colors. A pixel whose color components are (0, 0, 0) is displayed as black, and a
pixel whose color components are (1, 1, 1) i.e., (255, 255, 255) is displayed as white.
Grayscale Image:
Negative Image:
Negative image is a kind of image that can be formed by subtracting the RGB value from
255. The cv2.bitwise_not ( ) is used to convert the RGB color image into negative image in
color.
An RGB color image (i.e., positive image) is converted into a negative image using
R n = 255 – R p
G n = 255 - G p
B n = 255 – B p
where p and n are positive and negative, respectively.
Edge Image:
Edge detection includes a variety of mathematical methods that aim at identifying points
in a digital image at which the image brightness changes sharply or has discontinuities. The
points at which image brightness changes sharply are typically organized into a set of curved line
segments termed edges. Edges are often associated with the boundaries of objects in an image. In
this coding, Canny edge detection method is used to convert RGB image into edge image using
cv2.canny ( ).
Coding:
def gray_image():
global panelB
gray = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
gray = Image.fromarray(gray)
gray = ImageTk.PhotoImage(gray)
if panelB is None:
panelB = Label(image=gray)
panelB.image = gray
panelB.pack(side="left", padx=30, pady=60)
else:
panelB.configure(image=gray)
panelB.image = gray
def edge_image():
global panelB
gray = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
edge = cv2.Canny(gray, 50, 100)
edge = Image.fromarray(edge)
edge = ImageTk.PhotoImage(edge)
if panelB is None:
panelB = Label(image=edge)
panelB.image = edge
panelB.pack(side="left", padx=30, pady=60)
else:
panelB.configure(image=edge)
panelB.image = edge
def negative_image():
global panelB
image = cv2.cvtColor(image1, cv2.COLOR_BGR2RGB)
negative = cv2.bitwise_not(image)
negative = Image.fromarray(negative)
negative = ImageTk.PhotoImage(negative)
if panelB is None:
panelB = Label(image=negative)
panelB.image = negative
panelB.pack(side="left", padx=30, pady=60)
else:
panelB.configure(image=negative)
panelB.image = negative
root = Tk()
root.geometry('600x400')
fm = Frame(root, width=300, height=200)
fm.pack(side=BOTTOM, expand=NO, fill=NONE)
panelB = None
panel = None
btn = Button(root, text="Select an image", command=start,activebackground='red',fg="blue")
btn.pack(side="top")
btn2 = Button(fm, text="GRAY", command=gray_image,activebackground='red',height=2,
width=10,fg="gray")
btn2.pack(side=LEFT, padx="10", pady="20")
btn3 = Button(fm, text="EDGE", command=edge_image,activebackground='red',height=2,
width=10,fg="green")
btn3.pack(side=LEFT, padx="10", pady="20")
btn4 = Button(fm, text="NEGATIVE",
command=negative_image,activebackground='red',height=2, width=10,fg="purple")
btn4.pack(side=LEFT, padx="10", pady="20")
root.mainloop()
Result:
The given RGB color image is converted into grayscale, negative and edge images using Tkinter.
***