You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

未显式导入PIL却遇ModuleNotFoundError?matplotlib依赖问题求解

未显式导入PIL却触发「ModuleNotFoundError: No module named 'PIL'」的解决方法

错误原因

从错误栈可以明确看到,报错出在matplotlib.colors模块导入PIL.Image时——matplotlib内部部分功能依赖PIL库(即Pillow),即便你没有在代码里显式导入PIL,只要matplotlib加载到相关模块,就会尝试调用这个依赖,缺失时就会触发该错误。

解决方法

1. 确认虚拟环境并安装Pillow

你当前使用了虚拟环境(路径显示venv\Lib\site-packages),必须确保在激活虚拟环境后执行安装命令:

  • 激活虚拟环境:
    Windows系统:venv\Scripts\activate
    macOS/Linux系统:source venv/bin/activate
  • 安装Pillow:
    pip install pillow
    

2. 若安装后仍报错的排查步骤

  • 检查pip是否指向虚拟环境:执行which pip(macOS/Linux)或where pip(Windows),确认路径包含你的虚拟环境目录
  • 强制重新安装Pillow:
    pip install --force-reinstall pillow
    
  • 检查matplotlib版本兼容性:部分旧版matplotlib对Pillow版本有要求,可尝试升级matplotlib:
    pip install --upgrade matplotlib
    

用户提供的代码

# Created by Simon Ranger : December 15th 2022

"""
A general expense tracker that is displayed in table format as well as statistical format

How to use:
1. when prompt enter the data you want to be stored

Desired Output:
The user can add to a variety of lists relating to what expenses they wanted, food, general, etc. which will be both
displayed in a file and the terminal.
"""

# Imports required
from pandas import DataFrame as df, read_csv, DataFrame
import numpy as np
from matplotlib import pyplot as plt
from datetime import date

# create empty lists
GoodsOrServices: list | str = []
Prices: list | float = []
Dates: list | date = []
ExpenseType: list | str = []


# funct adding data to lists
def addingData(goodsOrServices: str, prices: int | float, dates, expenseType: str) -> None:
    # appending to the lists
    GoodsOrServices.append(goodsOrServices)
    Prices.append(prices)
    Dates.append(dates)
    ExpenseType.append(expenseType)


def reportData() -> DataFrame:
    expenseType = ""

    # creating the dataframe
    report = df()
    report["GoodsOfServices"] = GoodsOrServices
    report["Prices"] = Prices
    report["Dates"] = Dates
    report["ExpenseType"] = ExpenseType
    report.to_csv("Expenses.csv")

    # creating an array to loop through the data and pull the data for each section
    FoodP = []
    HouseP = []
    TravelP = []

    # reads the file that was created above
    with open("Expenses.csv"):
        read_csv("Expenses.csv", skiprows=1)

    for _ in enumerate(report):
        if expenseType == "Food":
            Prices.append(FoodP)
        elif expenseType == "Household":
            Prices.append(HouseP)
        elif expenseType == "Travel":
            Prices.append(TravelP)
        elif _:
            print(f"Error: Something went wrong!")

    # putting the data into a graph
    plt.plot(report)
    plt.legend()
    plt.show()

    return report


def main():
    # option menu for the user
    truth: int = 1
    user: str = (input(f"Please enter your name: "))

    while truth != 0:
        options = int(
            input(f"Welcome {user} to this interactive expense tracker!\nPlease select an option below:\n1. Add "
                  f"Food Expenses\n2. Household expenses\n3. Travel Expenses\n4. Display and Save the "
                  f"Expense Report\n0. Exit\nPlease enter the choice here: "))

        match options:
            case 0:
                exit(f"Thank you for using the Expense Tracker. See you next time!")
            case 1:
                print(f"Adding Food\n")
                expenseType = "Food"
            case 2:
                print(f"Adding Household\n")
                expenseType = "Household"
            case 3:
                print(f"Adding Travel\n")
                expenseType = "Travel"
            case 4:
                reportData()

        # lets the user enter the data
        if options == 1 or options == 2 or options == 3:
            goodsOrservices = str(input(f"Enter the goods or services for the expense type {expenseType}:\n")).strip()
            price = float(input(f"Enter the price of the goods or service:\n"))
            today = date.today()
            addingData(goodsOrservices, price, today, expenseType)


if __name__ == "__main__":
    main()

错误栈信息

Traceback (most recent call last):
  File "C:\Users\General\Desktop\Codes\Python\Programs\Advanced\ExpenseTracker.py", line 17, in <module>
    from matplotlib import pyplot as plt
  File "C:\Users\General\Desktop\Codes\Python\venv\Lib\site-packages\matplotlib\__init__.py", line 113, in <module>
    from . import _api, _version, cbook, _docstring, rcsetup
  File "C:\Users\General\Desktop\Codes\Python\venv\Lib\site-packages\matplotlib\rcsetup.py", line 27, in <module>
    from matplotlib.colors import Colormap, is_color_like
  File "C:\Users\General\Desktop\Codes\Python\venv\Lib\site-packages\matplotlib\colors.py", line 51, in <module>
    from PIL import Image
ModuleNotFoundError: No module named 'PIL'

内容的提问来源于stack exchange,提问作者simmo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:15:27