Last Updated :
05 May, 2025
When working with images in Python, many developers use the Pillow library, a modern fork of the old PIL (Python Imaging Library), to handle image processing tasks. However, you may encounter the error ModuleNotFoundError: No module named ‘PIL’, which can prevent your script from running. This usually occurs when Pillow is not installed properly or the import statement is incorrect. Let’s explore the common causes of this error and how to fix them step by step.
Why Does ModuleNotFoundError: No Module Named ‘PIL’ Occur?
Let’s understand the most common reasons for this error:
- PIL isn’t installed: PIL is outdated and replaced by Pillow, which should be installed instead.
- Incorrect import: Use from PIL import Image instead of import PIL—Pillow uses the PIL namespace for modules.
- Virtual environment issues: Ensure Pillow is installed in your active environment if you’re using one.
PIL vs. Pillow in Python
Understanding the difference between PIL and Pillow is important so you know which library to install and why pip install PIL won’t work. Let’s quickly compare them to clear up the confusion.
Feature |
PIL |
Pillow |
---|---|---|
Status |
Deprecated (no longer maintained) |
Actively maintained fork |
Installation |
Not available via pip |
Install with pip install Pillow |
Module Namespace |
Uses PIL |
Also uses PIL for backward compatibility |
Recommendation |
Recommendation |
Use Pillow |
How to Fix «ModuleNotFoundError: No Module Named ‘PIL'»?
Let’s understand a concise guide to resolving this issue:
1. Install Pillow: The most straightforward solution to the ModuleNotFoundError: No module named ‘PIL’ error is to install Pillow, which is the modern version of PIL. To install Pillow, open your terminal or command prompt and run the following command:
- For Python 2.x:
pip install Pillow
- For Python 3.x:
pip3 install Pillow
Once the installation is complete, Pillow will be ready to use.
2. Verifying the Installation: After installing Pillow, you can verify the installation by importing it in a Python script or an interactive Python session. Run the following commands to check if Pillow is correctly installed:
import PIL
print(PIL.__version__)
If the import is successful and the version number is printed, then Pillow is installed correctly.
3. Use the Correct Import Statement: If you’re trying to use image-related features and wrote import PIL, it might not work as expected. Instead, you should import specific modules from Pillow like this:
from PIL import Image
from PIL import ImageDraw, ImageFont
Example:
Python
from PIL import Image # Open an image file img = Image.open('example.jpg') img.show()
Output
4. Check Python Path: If Pillow is installed but still shows an error, Python may not be looking in the right place. You can check the current Python path using:
import sys
print(sys.path)
This will list all directories Python is searching for modules. Make sure the folder where Pillow is installed is included in the list. If it’s not there, your environment might not be configured correctly.
5. Using a Virtual Environment: If you’re using a virtual environment (which is great for keeping projects separate), remember that each environment needs its own packages. So, even if Pillow is installed globally, it won’t be available in your virtual environment unless you install it there. To activate your virtual environment:
- On Linux/Mac:
source venv/bin/activate
- On Windows:
venv\Scripts\activate
Then install Pillow in the environment:
pip install Pillow
6. Reinstall Pillow: If nothing else works, the installation might be broken or incomplete. Reinstalling usually fixes that. First, uninstall:
pip uninstall Pillow
Then, install it again:
pip install Pillow
Following these steps should help you fix the «ModuleNotFoundError: No module named ‘PIL'» error and get Pillow working smoothly in your Python projects!
Related Articles
- Pillow library
- PIL
- Virtual environment
Пройдите тест, узнайте какой профессии подходите
Работать самостоятельно и не зависеть от других
Работать в команде и рассчитывать на помощь коллег
Организовывать и контролировать процесс работы
Быстрый ответ
Если вы столкнулись с ошибкой ImportError
, то быстрое решение этой проблемы будет таким – установить Pillow, являющуюся актуализированной альтернативой устаревшей библиотеке PIL. Установка осуществляется с помощью команды:
Для работы с изображениями после установки данной библиотеки, следует использовать следующий синтаксис для импортирования модуля:
Не забывайте, что для Python 3 вместо команды pip
необходимо использовать pip3
.

Общее понимание ошибки ImportError
Болезненное сообщение ошибки ImportError: No module named PIL
возникает, когда в вашей среде Python отсутствует требуемая библиотека для обработки изображений. Ранее, роль такой библиотеки исполняла Python Imaging Library (PIL), но в силу остановленного развития комьюнити мигрировало на использование Pillow – более простого и дружественного форка PIL.
Почему предпочтительнее использовать Pillow а не PIL?
Переход на Pillow, к не только является решением ошибки ImportError, но и предоставляет доступ к улучшенным функциям, регулярным обновлениям, облегчает процесс работы благодаря юзабельности Pillow. Если после установки Pillow ошибка все еще преследует вас, может быть целесообразно проверить наличие нескольких установленных версий Python и возможность создания виртуального окружения.
Переход от PIL к Pillow
Чтобы корректно осуществить переход от PIL к Pillow, сначала удалите PIL с помощью команды pip uninstall PIL
. Затем установите Pillow выполните команду pip install Pillow
. Уточню, что в некоторых системах (например, под управлением Linux) или при возникновении проблем с правами доступа потребуется запуск установки от имени суперпользователя, воспользовавшись командой sudo
, например, следующим образом: sudo pip install Pillow
.
Визуализация
Можно представить ваше окружение Python в виде набора инструментов (🧰):
Было: [🔧, 🛠, ✂️, (📸 НЕТ)]
Основные шаги
- Установите Pillow (наследник PIL):
В вашем наборе инструментов появилась новая камера (📸)!
- Корректный синтаксис импорта модуля:
Основная идея
Без камеры (📸) вы не сможете фотографировать, поскольку будете получать ошибку ImportError. Но оснастившись в своем арсенале (🧰) необходимым инструментом, вы достигните своих целей без каких-либо препятствий!
Продвинутые методы устранения неполадок
Если вы уже выполнены все вышеперечисленные шаги, но проблема сохраняется, обратимся к дополнительным диагностическим методам и продвинутым способам решения.
Проверка несоответствия: анализ переменной PATH
Убедитесь, что переменная окружения PATH включает путь к директории, где установлен Python. В противном случае, окружение Python не сможет обнаружить модуль Pillow, что в резульатет приведет к ошибке ImportError.
Новое начало: обновление окружения
Иногда, чтобы устранить проблему, необходимо перезапустить все с успешного момента, создав новую среду для полной переустановки:
Поиск и устранение конфликтов: анализ проблем с пакетами
Осуществите анализ списка установленных пакетов с помощью команды pip freeze
. Иногда некоторые пакеты могут конфликтовать с Pillow.
Проверка бинарных зависимостей: анализ компонентов
Pillow требует наличия бинарных библиотек, таких как libjpeg и zlib. Гарантируйте, что эти библиотеки установлены в вашей системе. Обычно, они устанавливаются вместе с Pillow, но могут быть исключения.
Полезные материалы
- Руководство по установке Pillow (Форк PIL) 10.2.0 — полное руководство по установке Pillow.
- Pillow на PyPI — официальная страница Pillow на PyPI, содержащая информацию на темы от установки до истории создания проекта.
- Обсуждение установки PIL/Pillow на Mac OS через pip на Stack Overflow — содержит информацию о типичных ошибках при установке на Mac OS.
- Заметки о релизе Pillow 3.0.0 — подробная информация о совместимости с Python в новых релизах Pillow.
- Описание исключения ImportError в документации Python 3.12.1 — официальное объяснение ошибки ImportError.
- Руководство по установке пакетов от Python Packaging User Guide — максимально удобные методы и предложения по работе с пакетами Python.
- Создание виртуальных окружений при помощи venv в документации Python 3.12.1 — официальное руководство по созданию и использованию виртуальных окружений Python.
If you’ve encountered the error «ModuleNotFoundError: No module named ‘PIL'» when trying to import the Python Imaging Library (PIL) in your Python script, don’t worry. This article will guide you through several solutions to resolve this common issue.
For a general overview of solving ModuleNotFoundErrors in Python, you can also check out our guide on How To Solve ModuleNotFoundError: No module named in Python.
Understanding the Error
This error occurs when Python can’t find the PIL library in its search path. There are two primary reasons for this:
- PIL (or its fork, Pillow) is not installed in your current Python environment.
- Your script is running in an environment where PIL is not accessible.
Solution 1: Installing Pillow
The most straightforward solution is to install Pillow, which is the modern fork of PIL, using pip:
pip install Pillow
Note that ‘PIL’ is the import name, but the package name is ‘Pillow’.
Solution 2: Using the Correct Python Environment
If you’re using virtual environments or conda, ensure you’re activating the correct environment where Pillow is installed:
# For virtual environments
source myenv/bin/activate # On Unix or MacOS
myenv\Scripts\activate # On Windows
# For conda environments
conda activate myenv
Solution 3: Verifying the Installation
To confirm that Pillow is correctly installed, run these Python commands:
import sys
print(sys.executable)
from PIL import Image
print(Image.__version__)
This will print the path to your Python interpreter and the version of Pillow if it’s installed correctly.
Solution 4: Installing Pillow with Anaconda
If you’re using Anaconda, you can install Pillow using conda:
conda install pillow
Solution 5: Checking Python Path
Ensure that the directory containing Pillow is in your Python path:
import sys
print(sys.path)
# If needed, add the path where Pillow is installed
import site
site.addsitedir("/path/to/site-packages")
Solution 6: Reinstalling Pillow
If issues persist, try uninstalling and reinstalling Pillow:
pip uninstall Pillow
pip install Pillow
Solution 7: Installing Dependencies
Pillow may require additional system libraries. On Unix-based systems, you might need to install these dependencies:
sudo apt-get install libjpeg-dev zlib1g-dev
Then reinstall Pillow:
pip install --no-cache-dir Pillow
Solution 8: Using a Requirements File
If you’re working on a project, consider using a requirements.txt file:
# Create requirements.txt with Pillow
echo "Pillow" > requirements.txt
# Install from requirements.txt
pip install -r requirements.txt
Troubleshooting Tips
- Ensure you’re using a compatible Python version. Check Pillow’s documentation for supported Python versions.
- If using an IDE, restart it after installing Pillow to ensure it recognizes the new installation.
- Check for any error messages during the Pillow installation process, as they might provide clues about specific issues.
- On Windows, verify that the Python Scripts directory is in your system’s PATH.
- If you’re behind a proxy, ensure your pip is configured correctly to use the proxy.
Common Pitfalls
- Mixing pip and conda installations can lead to conflicts. Stick to one package manager within an environment.
- Installing Pillow globally instead of in a virtual environment can sometimes cause issues, especially if you have multiple Python versions.
- On macOS, using the system Python instead of a separately installed Python distribution can sometimes cause problems.
- Confusing ‘PIL’ (the import name) with ‘Pillow’ (the package name) when installing.
Advanced Usage: Importing Specific Modules
Remember that ‘PIL’ is just the root package. You often need to import specific modules:
from PIL import Image
from PIL import ImageFilter
from PIL import ImageEnhance
Version Compatibility
If you’re working on a specific project or tutorial, make sure you’re using the correct version of Pillow:
pip install Pillow==8.2.0 # Install a specific version
Conclusion
The «ModuleNotFoundError: No module named ‘PIL'» is a common hurdle when setting up image processing projects with Python. By following these steps, you should be able to successfully install Pillow and import it in your Python scripts.
Remember that managing Python environments and dependencies is crucial for smooth development, especially with libraries like Pillow that may require system-level dependencies.
Always refer to the official Pillow documentation for the most up-to-date installation instructions and compatibility information.
For more information on solving ModuleNotFoundErrors in Python, don’t forget to check out our comprehensive guide: How To Solve ModuleNotFoundError: No module named in Python.
If you use the Python image library and import PIL, you might get ImportError: No module named PIL while running the project. It happens due to the depreciation of the PIL library. Instead, it would help if you install and use its successor pillow library to resolve the issue.
If you use Python version 3 and try to install and use the PIL library, you will get the ImportError: No module named PIL while importing it, as shown below.
PIL is the Python Imaging Library developed by Fredrik Lundh and Contributors. Currently, PIL is depreciated, and Pillow is the friendly PIL fork by Alex Clark and Contributors. As of 2019, Pillow development is supported by Tidelift.
How to fix ImportError: No module named PIL?
If you are using Python version 3, the best way to resolve this is by uninstalling the existing PIL package and performing a clean installation of the Pillow package, as shown below.
Step 1: Uninstall the PIL package.
pip uninstall PIL
Step 2: Install the Pillow using pip as shown below on different operating systems.
On Windows
python3 -m pip install --upgrade pip
python3 -m pip install --upgrade Pillow
On Linux
easy_install Pillow
On OSX
brew install Pillow
Note: Sometimes, while importing matplotlib in your Jupyter notebook, you might face this issue and doing a standard install of Pillow may not work out. You could do a force install of Pillow, as shown below, to resolve the error.
pip install --upgrade --force-reinstall Pillow
pip install --upgrade --force-reinstall matplotlib
Step 3: The most crucial class in the Python Imaging Library is the Image class, and you can import this as shown below.
from PIL import Image
im = Image.open("myimage.jpg")
If successful, this function returns an Image object. You can now use instance attributes to examine the file contents:
print(im.format, im.size, im.mode)
#Output: PPM (512, 512) RGB
Note: If you use Python version 2.7, you need to install image and Pillow packages to resolve the issue.
python -m pip install image
python -m pip install Pillow
Python Image Library or PIL is an image processing module developed for Python. It provides image processing tools that help in creating, editing, and exporting image files. However, the PIL project was abandoned in 2011. To continue providing support for the latest Python versions, the Pillow module forked the PIL module. The Pillow module eventually replaced PIL and became the go-to image processing library for Python.
The Python interpreter may not detect specific modules when imported. Therefore, upon execution, Python will return the ModuleNotFoundError: No module named 'pil'
exception and exits the program.
For example, let’s say we’re importing a package called “run”. We would do so by using the import statement followed by the package name; run. Since there is no module called “run”, this error is shown.
Causes & Solutions For No Module Named Pil
There are multiple reasons why this exception may be raised. Let’s look at the following instances.
Package Not Installed Properly
This is probably the most typical reason for this exception. Some libraries may not be part of the Python Standard Library. Therefore they require additional installation steps before we can use them.
In specific IDEs (e.g., spyder), make sure your module are all installed in a single folder. PIP installer may install your package in one place, whereas the IDE expects the module in another directory. Make sure to save all external dependencies in one place.
It is vital to ensure that the correct installation commands for provided to install Pillow.
Windows Installationpython3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow
macOS Installationpython3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow
Linux Installationpython3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow
Multiple Python Versions Installed
Installing multiple versions of Python can result in multiple library folders for each version. Therefore, ensure the library is present in the correct version of Python.
Here’s how we can find the installation location for your version of Python
Open up the Python command terminal
Type the following lines of commands
import os import sys os.path.dirname(sys.executable)
Output
So the location would be: ‘C:\Users\Admin\AppData\Local\Programs\Python\Python310’
Incorrect Package Name
Certain packages have import statements that are different from their actual names. One notable example is a web scraping library called BeautifulSoup
. The common user may attempt to import the module by calling import BeautifulSoup
.
However, this is incorrect. You must go through the documents of each module and figure out the correct import command to avoid confusion. Furthermore, the correct implementation for the said example would be: import bs4
Importing Files
Another reason for the error to arise is importing Python files incorrectly. For example, let’s assume we’re importing the file “program.py”. To import this, we run “import program
” excluding the .py
extension. It is also essential to ensure that the file is present in the working directory. If failed to do so, the following error will appear:
Another rule to remember is that do not use names of pre-existing packages as your Python file name i.e pil.py
. If done otherwise, the Python interpreter will consider pandas as your Python file rather than the pil
package itself. This will cause problems when working with your file and the package.
Python No Module Named Pil Visual Studio Code
Users tend to face an issue with the module in VSCode. Upon importing, the program may run perfectly, but under the problems tab, this may appear:
import PIL could not be resolved from source. Pylance(reportmissingmodulesource)
This error is caused due to the fact that VS Code isn’t running the same Python interpreter between the two or more versions. Modules are installed on one of the Python versions you have. Therefore, we must determine the path to the Python executable. Refer to the following command
import sys print(sys.executable)
This will show us the location in which Python is installed. If you run the same command on VS Code, it will show a different location. In order to have the versions in the same location, we must install the Python interpreter that is being used by VS Code. Type this in your terminal
/path/to/python/used/by/vs/code/python -m pip install pillow
No Module Named pil.imagetk
For Versions Below Python 3
This is due to the fact that Python is installed in a different location than the standard one. This can be fixed by re-installing Python to the standard location or by appending the location to sys.path
.
For Versions Above Python 3
Python 3 and above imagetk
comes under the Pillow module. Therefore, in order to import, run the following command.
PIL is a deprecated project, and no further support is provided. However, the Pillow project forked PIL to provide support for the latest Python versions. For macOS machines, the following command needs to be entered.
sudo pip install pillow
In some instances, the following error may appear.
ImportError: No module named PIL
An easy solution to this problem is to make sure PIP
is upgraded to the latest versions. PIP
makes sure all your packages are unzipped and loaded into Python, ready to use. Therefore, it is vital to upgrade PIP
in order to install the latest versions of modules. You can upgrade PIP
using the following command in macOS
sudo pip install --upgrade pip
No Module Named PIL (Ubuntu)
In some versions of PIL
in Ubuntu, it may come under the name imaging. Therefore in order to install Pillow in Ubuntu, run the following command.
sudo apt-get install python-imaging
No Module Named PIL (Raspberry Pi)
Upon installing the module on your Pi 0, you may be presented with the following error
sudo apt-get install python-pillow python-pil Reading package lists... Done Building dependency tree Reading state information... Done Note, selecting 'python-pil' instead of 'python-pillow' python-pil is already the newest version (5.4.1-2+deb10u2). 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Despite the successful installation, you may be presented with No Module Named Pil
error upon running your Python file.
This may be due to the fact that the version of PIL and Python do not match. Make sure your Pi has the correct version of Python installed, and it makes sure the PIL installation matches your Python version.
Upon installation, the .exiftags
function may not work. This may be due to the fact that other versions of the same module may cause the file to be deleted or overwritten.
Deleting all module versions and only saving the latest one can fix this issue.
FAQs
The module name is Pillow, but we use pil to import it. Why?
Support for Python Image Library has been discontinued. Therefore, for the module to work on newer Python versions, the Pillow project forked the existing PIL project. All functionalities from PIL are present in Pillow as well.
How to add pillow in requirements.txt?
Add RUN apk add zlib-dev jpeg-dev gcc musl-dev
within your docker file and add Pillow within the requirements.txt
file
What is the use of the Pillow module in Python?
Pillow provides image processing capabilities for Python. It has multiple file format support and powerful image processing abilities.
Conclusion
We’ve gone through various causes for Python No Module Named Pil exception. Make sure to keep these reasons in mind, as most “No Module Named” errors have similar reasons.
Trending Python Articles
-
[Fixed] typeerror can’t compare datetime.datetime to datetime.date
●January 11, 2024
-
[Fixed] nameerror: name Unicode is not defined
by Namrata Gulati●January 2, 2024
-
[Solved] runtimeerror: cuda error: invalid device ordinal
by Namrata Gulati●January 2, 2024
-
[Fixed] typeerror: type numpy.ndarray doesn’t define __round__ method
by Namrata Gulati●January 2, 2024