Pyinstaller matplotlib error

Issue I have this script that I attached a GUI to the front of and wanted to distribute it...

Issue

I have this script that I attached a GUI to the front of and wanted to distribute it to other DnD DMs for them to use to overlay grids onto images. Only issue is that everytime I try to package the python script using Pyinstaller, it keeps throwing two different errors. If I run pyinstaller --hidden-import matplotlib myscript.py it returns

    NameError: name 'defaultParams' is not defined
    [7532] Failed to execute script ImageGridder

So I decided to try and run the command again with the --onefile option. When I do so it returns,

   RuntimeError: Could not find the matplotlib data files
   [18884] Failed to execute script ImageGridder

Now in both examples, the packaging process completes, and all of the files seem to be generated correctly. It’s just when I run the .exe it generates, it crashes. I know the file itself runs properly as I have gotten it to run and work properly on both my desktop and laptop. I’ve done a good few hours of searching for anything that would help, but nothing really seems to work. The script itself,

from PIL import Image
import tkinter as tk
from tkinter import filedialog
import matplotlib.pyplot as PLT
import matplotlib.ticker as plticker

class gridder(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.initialize()

    def initialize(self):        
        self.iWidth = tk.StringVar()
        self.iHeight = tk.StringVar()
        self.imgSelect = tk.StringVar()
        self.squareLength= tk.IntVar()
        self.ratioX=tk.IntVar()
        self.ratioY=tk.IntVar()
        self.checkSquare = tk.IntVar()
        self.colorLine= tk.StringVar()
        
        self.colorLine.set('k')
        self.checkSquare.set(0)
        self.ratioX.set(10)
        self.ratioY.set(10)
        self.squareLength.set(120)
        

        # row 1
        labelDisclaim = tk.Label(self, text='Currently only works with jpegs')
        labelDisclaim.grid(column=2, row=1)

        # row 2
        buttonOpen = tk.Button(self, text="Select an Image", command=self.openExplorer)
        buttonOpen.grid(column=1, row=2)

        labelSelected= tk.Label(self, text="Selected Image: ")
        labelSelected.grid(column=2,row=2)

        labelImgName = tk.Label(self, textvariable=self.imgSelect)
        labelImgName.grid(column=3,row=2)
        

        # row 3
        labelStaticImg= tk.Label(self, text="Width of image, in pixels: ")
        labelStaticImg.grid(column=1,row=3)

        labelImgWidth = tk.Label(self, textvariable=self.iWidth, anchor='w')
        labelImgWidth.grid(column=2,row=3)

        labelStaticHeight= tk.Label(self, text="Height of image, in pixels: ")
        labelStaticHeight.grid(column=3,row=3)

        labelImgHeight = tk.Label(self, textvariable=self.iHeight, anchor='w')
        labelImgHeight.grid(column=4,row=3)

        # row 4
        labelRatioX = tk.Label(self, text="Enter the Ratio along the X axis, default is 10: ")
        labelRatioX.grid(column=1,row=4)

        entryRatioX = tk.Entry(self, textvariable=self.ratioX)
        entryRatioX.grid(column=2,row=4)

        labelRatioY =tk.Label(self, text="Enter the Ratio along the Y axis, default is 10: ")
        labelRatioY.grid(column=3,row=4)

        entryRatioY = tk.Entry(self, textvariable=self.ratioY)
        entryRatioY.grid(column=4,row=4)

        # row 5
        labelSquare = tk.Label(self, text="For strict squares, in the sense of a battle map, check this ->")
        labelSquare.grid(column=1,row=5)

        checkboxSquare = tk.Checkbutton(self, variable=self.checkSquare, text="If checked, it will ignore the ratio and apply squares that are specified by the entry, (default 120x120) ->",wraplength=150)
        checkboxSquare.grid(column=2,row=5)

        labelSquareLength = tk.Label(self, text="Side length of Square: ")
        labelSquareLength.grid(column=3,row=5)

        entrySquareLength = tk.Entry(self, textvariable=self.squareLength)
        entrySquareLength.grid(column=4,row=5)

        
        # row 6
        labelColor= tk.Label(self, text="Enter a color for the grid, valid choices black=k, blue=b, green=g, red=r, white=w, brown=brown, yellow=yellow, cyan=c. Default is black: ",wraplength=250)
        labelColor.grid(column=1,row=6)

        entryColor = tk.Entry(self, textvariable=self.colorLine)
        entryColor.grid(column=2,row=6)
        
        execButton = tk.Button(self, text="Gridify", command=self.gridify)
        execButton.grid(column=4,row=6)
        
        # row 9
        button = tk.Button(self,text="Exit",command=self.closeProgram)
        button.grid(column=2,row=9)

        # row 10
        labelSig = tk.Label(self, text='By Johnathan Keith, 2020. Ver 1.0. This is free-to-use, and will always be. This was willingly distributed to the public.',wraplength=350)
        labelSig.grid(column=2,row=10)

        labelDisclaimer = tk.Label(self, text="This program does NOT generate pop up windows for bad data entries. If the image does not generate into the folder the script is in, you did something wrong.",wraplength=200)
        labelDisclaimer.grid(column=4,row=10)

    def openFile(self, imagefilename):
        Img = Image.open(imagefilename)
        height, width = Img.size
        self.iHeight.set(height)
        self.iWidth.set(width)

    def gridify(self):
        ratioX=0
        ratioY=0
        sidelengthy=0
        sidelengthx=0
        if self.checkSquare.get():
            ratioX=int(self.squareLength.get())
            ratioY=int(self.squareLength.get())
            sidelengthx=ratioX
            sidelengthy=ratioY
        else:
            ratioX=int(self.ratioX.get())
            ratioY=int(self.ratioY.get())
            sidelengthy=int(self.iWidth.get())/ratioY
            sidelengthx=int(self.iHeight.get())/ratioX
        image=Image.open(self.imgSelect.get())
        my_dpi=300.

        #set the figure up
        fig=PLT.figure(figsize=(float(image.size[0])/my_dpi,float(image.size[1])/my_dpi),dpi=my_dpi)
        ax=fig.add_subplot(111)

        #remove whitespace
        fig.subplots_adjust(left=0,right=1,bottom=0,top=1)

        #set gridding interval
        locx = plticker.MultipleLocator(base=sidelengthx)
        locy = plticker.MultipleLocator(base=sidelengthy)
        ax.xaxis.set_major_locator(locx)
        ax.yaxis.set_major_locator(locy)

        #add the grid
        ax.grid(which='major', axis='both', linestyle='-',color=self.colorLine.get())

        ax.imshow(image)

        token=self.imgSelect.get().split('/')
        saveName= "gridded_"+token[-1]
        
        # Save the figure
        fig.savefig(saveName,dpi=my_dpi)

    def closeProgram(self):
        self.destroy()
        exit()

    def dataEntry(self):
        if type(int) == type(int(bHeight)):
            self.bHeight = int(entryHeight.get())
        else:
            return
        
    def openExplorer(self):
        filename= filedialog.askopenfilename(initialdir="/", title="Select an Image", filetypes=(("jpeg files", "*.jpg"),("all files", "*.*")))
        if filename:
           self.imgSelect.set(filename)
           self.openFile(filename)
           

if __name__ == "__main__":
    app = gridder()
    app.title('Image Gridder')
    app.mainloop()

I am running python 3.8, matplotlib 3.3.0, tkinter, and PIL 6.2.2, and pyinstaller 3.6.

The contents of the warning file while using the --onefile command:


This file lists modules PyInstaller was not able to find. This does not
necessarily mean this module is required for running you program. Python and
Python 3rd-party packages include a lot of conditional or optional modules. For
example the module 'ntpath' only exists on Windows, whereas the module
'posixpath' only exists on Posix systems.

Types if import:
* top-level: imported at the top-level - look at these first
* conditional: imported within an if-statement
* delayed: imported from within a function
* optional: imported within a try-except-statement

IMPORTANT: Do NOT post this list to the issue-tracker. Use it as a basis for
           yourself tracking down the missing module. Thanks!

missing module named _posixsubprocess - imported by subprocess (optional), multiprocessing.util (delayed)
missing module named 'org.python' - imported by copy (optional), xml.sax (delayed, conditional), setuptools.sandbox (conditional)
missing module named _frozen_importlib_external - imported by importlib._bootstrap (delayed), importlib (optional), importlib.abc (optional), zipimport (top-level)
excluded module named _frozen_importlib - imported by importlib (optional), importlib.abc (optional), zipimport (top-level), PyInstaller.loader.pyimod02_archive (delayed, conditional)
missing module named urllib.pathname2url - imported by urllib (conditional), PyInstaller.lib.modulegraph._compat (conditional)
missing module named _posixshmem - imported by multiprocessing.resource_tracker (conditional), multiprocessing.shared_memory (conditional)
missing module named multiprocessing.set_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
missing module named multiprocessing.get_start_method - imported by multiprocessing (top-level), multiprocessing.spawn (top-level)
missing module named _scproxy - imported by urllib.request (conditional)
missing module named termios - imported by tty (top-level), getpass (optional)
missing module named resource - imported by posix (top-level), test.support (optional)
missing module named 'java.lang' - imported by platform (delayed, optional), xml.sax._exceptions (conditional)
missing module named vms_lib - imported by platform (delayed, conditional, optional)
missing module named java - imported by platform (delayed)
missing module named _winreg - imported by platform (delayed, optional), numpy.distutils.cpuinfo (delayed, conditional, optional), pkg_resources._vendor.appdirs (delayed, conditional)
missing module named multiprocessing.get_context - imported by multiprocessing (top-level), multiprocessing.pool (top-level), multiprocessing.managers (top-level), multiprocessing.sharedctypes (top-level)
missing module named multiprocessing.TimeoutError - imported by multiprocessing (top-level), multiprocessing.pool (top-level)
missing module named multiprocessing.BufferTooShort - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
missing module named multiprocessing.AuthenticationError - imported by multiprocessing (top-level), multiprocessing.connection (top-level)
missing module named asyncio.DefaultEventLoopPolicy - imported by asyncio (delayed, conditional), asyncio.events (delayed, conditional)
missing module named readline - imported by cmd (delayed, conditional, optional), code (delayed, conditional, optional), pdb (delayed, optional)
missing module named org - imported by pickle (optional)
missing module named grp - imported by shutil (optional), tarfile (optional), pathlib (delayed), distutils.archive_util (optional)
missing module named pwd - imported by posixpath (delayed, conditional), shutil (optional), tarfile (optional), pathlib (delayed, conditional, optional), http.server (delayed, optional), webbrowser (delayed), netrc (delayed, conditional), getpass (delayed), distutils.util (delayed, conditional, optional), distutils.archive_util (optional)
missing module named posix - imported by os (conditional, optional), shutil (conditional)
missing module named 'multiprocessing.forking' - imported by C:UsersOwnerAppDataLocalProgramsPythonPython38-32Libsite-packagesPyInstallerloaderrthookspyi_rth_multiprocessing.py (optional)
missing module named 'win32com.gen_py' - imported by win32com (conditional, optional), C:UsersOwnerAppDataLocalProgramsPythonPython38-32Libsite-packagesPyInstallerloaderrthookspyi_rth_win32comgenpy.py (top-level)
missing module named pyimod03_importers - imported by PyInstaller.loader.pyimod02_archive (delayed, conditional), C:UsersOwnerAppDataLocalProgramsPythonPython38-32Libsite-packagesPyInstallerloaderrthookspyi_rth_pkgres.py (top-level)
missing module named 'pkg_resources.extern.pyparsing' - imported by pkg_resources._vendor.packaging.requirements (top-level), pkg_resources._vendor.packaging.markers (top-level)
missing module named _uuid - imported by uuid (optional)
missing module named __builtin__ - imported by PIL.Image (optional), numpy.core.numerictypes (conditional), numpy.core.numeric (conditional), numpy.lib.function_base (conditional), numpy.lib._iotools (conditional), numpy.ma.core (conditional), numpy.distutils.misc_util (delayed, conditional), numpy (conditional), pyparsing (conditional), pkg_resources._vendor.pyparsing (conditional), setuptools._vendor.pyparsing (conditional)
missing module named ordereddict - imported by pyparsing (optional), pkg_resources._vendor.pyparsing (optional), setuptools._vendor.pyparsing (optional)
missing module named StringIO - imported by PyInstaller.lib.modulegraph._compat (conditional), PyInstaller.lib.modulegraph.zipio (conditional), setuptools._vendor.six (conditional), numpy.lib.utils (delayed, conditional), numpy.lib.format (delayed, conditional), numpy.testing._private.utils (conditional), six (conditional), pkg_resources._vendor.six (conditional)
missing module named 'com.sun' - imported by pkg_resources._vendor.appdirs (delayed, conditional, optional)
missing module named com - imported by pkg_resources._vendor.appdirs (delayed)
missing module named pkg_resources.extern.packaging - imported by pkg_resources.extern (top-level), pkg_resources (top-level)
missing module named pkg_resources.extern.appdirs - imported by pkg_resources.extern (top-level), pkg_resources (top-level)
missing module named 'pkg_resources.extern.six.moves' - imported by pkg_resources (top-level), pkg_resources._vendor.packaging.requirements (top-level)
missing module named pkg_resources.extern.six - imported by pkg_resources.extern (top-level), pkg_resources (top-level), pkg_resources.py31compat (top-level)
missing module named pytest - imported by numpy._pytesttester (delayed), matplotlib (delayed, optional)
missing module named commands - imported by numpy.distutils.cpuinfo (conditional)
missing module named setuptools.extern.packaging - imported by setuptools.extern (top-level), setuptools.dist (top-level), setuptools.command.egg_info (top-level)
missing module named 'setuptools.extern.six' - imported by setuptools (top-level), setuptools.extension (top-level)
missing module named 'setuptools.extern.packaging.version' - imported by setuptools.config (top-level), setuptools.msvc (top-level)
missing module named setuptools.extern.six.moves.filterfalse - imported by setuptools.extern.six.moves (top-level), setuptools.dist (top-level), setuptools.msvc (top-level)
missing module named setuptools.extern.six.moves.filter - imported by setuptools.extern.six.moves (top-level), setuptools.dist (top-level), setuptools.ssl_support (top-level), setuptools.command.py36compat (top-level)
missing module named _manylinux - imported by setuptools.pep425tags (delayed, optional)
missing module named 'setuptools.extern.packaging.utils' - imported by setuptools.wheel (top-level)
missing module named wincertstore - imported by setuptools.ssl_support (delayed, optional)
missing module named 'backports.ssl_match_hostname' - imported by setuptools.ssl_support (optional)
missing module named backports - imported by setuptools.ssl_support (optional)
missing module named 'setuptools._vendor.six.moves' - imported by 'setuptools._vendor.six.moves' (top-level)
missing module named 'setuptools.extern.pyparsing' - imported by setuptools._vendor.packaging.markers (top-level), setuptools._vendor.packaging.requirements (top-level)
missing module named setuptools.extern.six.moves.map - imported by setuptools.extern.six.moves (top-level), setuptools.dist (top-level), setuptools.command.easy_install (top-level), setuptools.sandbox (top-level), setuptools.package_index (top-level), setuptools.ssl_support (top-level), setuptools.command.egg_info (top-level), setuptools.namespaces (top-level)
runtime module named setuptools.extern.six.moves - imported by setuptools.dist (top-level), setuptools.py33compat (top-level), configparser (top-level), setuptools.command.easy_install (top-level), setuptools.sandbox (top-level), setuptools.command.setopt (top-level), setuptools.package_index (top-level), setuptools.ssl_support (top-level), setuptools.command.egg_info (top-level), setuptools.command.py36compat (top-level), setuptools.namespaces (top-level), setuptools.msvc (top-level), 'setuptools._vendor.six.moves' (top-level)
missing module named setuptools.extern.six - imported by setuptools.extern (top-level), setuptools.monkey (top-level), setuptools.dist (top-level), setuptools.extern.six.moves (top-level), setuptools.py33compat (top-level), setuptools.config (top-level), setuptools.command.easy_install (top-level), setuptools.sandbox (top-level), setuptools.py27compat (top-level), setuptools.package_index (top-level), setuptools.wheel (top-level), setuptools.pep425tags (top-level), setuptools.command.egg_info (top-level), setuptools.command.sdist (top-level), setuptools.command.bdist_egg (top-level), setuptools.unicode_utils (top-level), setuptools.command.develop (top-level)
missing module named 'numpy_distutils.cpuinfo' - imported by numpy.f2py.diagnose (delayed, conditional, optional)
missing module named 'numpy_distutils.fcompiler' - imported by numpy.f2py.diagnose (delayed, conditional, optional)
missing module named 'numpy_distutils.command' - imported by numpy.f2py.diagnose (delayed, conditional, optional)
missing module named numpy_distutils - imported by numpy.f2py.diagnose (delayed, optional)
missing module named __svn_version__ - imported by numpy.f2py.__version__ (optional)
missing module named numarray - imported by numpy.distutils.system_info (delayed, conditional, optional)
missing module named Numeric - imported by numpy.distutils.system_info (delayed, conditional, optional)
missing module named ConfigParser - imported by numpy.distutils.system_info (conditional), numpy.distutils.npy_pkg_config (conditional)
missing module named _curses - imported by curses (top-level), curses.has_key (top-level)
missing module named _dummy_threading - imported by dummy_threading (optional)
missing module named 'nose.plugins' - imported by numpy.testing._private.noseclasses (top-level), numpy.testing._private.nosetester (delayed)
missing module named scipy - imported by numpy.testing._private.nosetester (delayed, conditional)
missing module named 'nose.util' - imported by numpy.testing._private.noseclasses (top-level)
missing module named nose - imported by numpy.testing._private.utils (delayed, optional), numpy.testing._private.decorators (delayed), numpy.testing._private.noseclasses (top-level)
missing module named dummy_thread - imported by numpy.core.arrayprint (conditional, optional)
missing module named thread - imported by numpy.core.arrayprint (conditional, optional), PyInstaller.loader.pyimod02_archive (conditional)
missing module named cPickle - imported by numpy.core.numeric (conditional)
missing module named cStringIO - imported by cPickle (top-level)
missing module named copy_reg - imported by cPickle (top-level), cStringIO (top-level), numpy.core (conditional)
missing module named pickle5 - imported by numpy.core.numeric (conditional, optional)
missing module named numpy.core.number - imported by numpy.core (delayed), numpy.testing._private.utils (delayed)
missing module named numpy.core.signbit - imported by numpy.core (delayed), numpy.testing._private.utils (delayed)
missing module named numpy.core.float64 - imported by numpy.core (delayed), numpy.testing._private.utils (delayed)
missing module named numpy.core.float32 - imported by numpy.core (top-level), numpy.testing._private.utils (top-level)
missing module named numpy.lib.i0 - imported by numpy.lib (top-level), numpy.dual (top-level)
missing module named numpy.core.integer - imported by numpy.core (top-level), numpy.fft.helper (top-level)
missing module named numpy.core.sqrt - imported by numpy.core (top-level), numpy.linalg.linalg (top-level), numpy.fft.fftpack (top-level)
missing module named numpy.core.conjugate - imported by numpy.core (top-level), numpy.fft.fftpack (top-level)
missing module named numpy.core.divide - imported by numpy.core (top-level), numpy.linalg.linalg (top-level)
missing module named numpy.core.object_ - imported by numpy.core (top-level), numpy.linalg.linalg (top-level)
missing module named numpy.core.intp - imported by numpy.core (top-level), numpy.linalg.linalg (top-level)
missing module named numpy.core.geterrobj - imported by numpy.core (top-level), numpy.linalg.linalg (top-level)
missing module named numpy.core.add - imported by numpy.core (top-level), numpy.linalg.linalg (top-level)
missing module named numpy.core.complexfloating - imported by numpy.core (top-level), numpy.linalg.linalg (top-level)
missing module named numpy.core.inexact - imported by numpy.core (top-level), numpy.linalg.linalg (top-level)
missing module named numpy.core.cdouble - imported by numpy.core (top-level), numpy.linalg.linalg (top-level)
missing module named numpy.core.csingle - imported by numpy.core (top-level), numpy.linalg.linalg (top-level)
missing module named numpy.core.double - imported by numpy.core (top-level), numpy.linalg.linalg (top-level)
missing module named numpy.core.single - imported by numpy.core (top-level), numpy.linalg.linalg (top-level)
missing module named future_builtins - imported by numpy.lib.npyio (conditional)
missing module named urllib2 - imported by numpy.lib._datasource (delayed, conditional)
missing module named urlparse - imported by numpy.lib._datasource (delayed, conditional)
missing module named numpy.recarray - imported by numpy (top-level), numpy.ma.mrecords (top-level)
missing module named numpy.dtype - imported by numpy (top-level), numpy.ma.mrecords (top-level), numpy.ctypeslib (top-level)
missing module named numpy.expand_dims - imported by numpy (top-level), numpy.ma.core (top-level)
missing module named numpy.array - imported by numpy (top-level), numpy.ma.core (top-level), numpy.ma.extras (top-level), numpy.ma.mrecords (top-level), numpy.ctypeslib (top-level)
missing module named numpy.bool_ - imported by numpy (top-level), numpy.ma.core (top-level), numpy.ma.mrecords (top-level)
missing module named numpy.iscomplexobj - imported by numpy (top-level), numpy.ma.core (top-level)
missing module named numpy.amin - imported by numpy (top-level), numpy.ma.core (top-level)
missing module named numpy.amax - imported by numpy (top-level), numpy.ma.core (top-level)
missing module named numpy.ndarray - imported by numpy (top-level), numpy.ma.core (top-level), numpy.ma.extras (top-level), numpy.ma.mrecords (top-level), numpy.ctypeslib (top-level)
missing module named numpy.histogramdd - imported by numpy (delayed), numpy.lib.twodim_base (delayed)
missing module named numpy.eye - imported by numpy (delayed), numpy.core.numeric (delayed)
missing module named six.moves.zip - imported by six.moves (top-level), cycler (top-level)
runtime module named six.moves - imported by cycler (top-level), dateutil.tz.tz (top-level), dateutil.tz._factories (top-level), dateutil.tz.win (top-level), dateutil.rrule (top-level)
missing module named six.moves.range - imported by six.moves (top-level), dateutil.rrule (top-level)
missing module named colorama - imported by tornado.log (optional)
missing module named typing_extensions - imported by tornado.ioloop (conditional), tornado.websocket (conditional)
missing module named fcntl - imported by tornado.platform.posix (top-level)
missing module named dateutil.tz.tzfile - imported by dateutil.tz (top-level), dateutil.zoneinfo (top-level)
missing module named shiboken - imported by matplotlib.backends.qt_compat (delayed, conditional)
missing module named PySide - imported by matplotlib.backends.qt_compat (delayed, conditional)
missing module named PyQt4 - imported by matplotlib.backends.qt_compat (delayed)
missing module named shiboken2 - imported by matplotlib.backends.qt_compat (delayed, conditional)
missing module named PySide2 - imported by PIL.ImageQt (conditional, optional), matplotlib.backends.qt_compat (delayed, conditional)
missing module named sip - imported by matplotlib.backends.qt_compat (delayed, conditional, optional), PyQt5 (top-level)
missing module named matplotlib.axes.Axes - imported by matplotlib.axes (top-level), matplotlib.pyplot (top-level), matplotlib.legend (delayed), matplotlib.projections.geo (top-level), matplotlib.projections.polar (top-level), mpl_toolkits.mplot3d.axes3d (top-level), matplotlib.figure (top-level)
missing module named 'IPython.core' - imported by matplotlib.backend_bases (delayed), matplotlib.pyplot (delayed, conditional, optional)
missing module named IPython - imported by matplotlib.backend_bases (delayed), matplotlib.pyplot (delayed, conditional, optional)
missing module named matplotlib.tri.Triangulation - imported by matplotlib.tri (top-level), matplotlib.tri.trifinder (top-level), matplotlib.tri.tritools (top-level), matplotlib.tri.triinterpolate (top-level)
missing module named matplotlib.axes.Subplot - imported by matplotlib.axes (top-level), matplotlib.pyplot (top-level)
missing module named olefile - imported by PIL.MicImagePlugin (top-level), PIL.FpxImagePlugin (top-level)
missing module named UserDict - imported by PIL.PdfParser (optional)
missing module named Tkinter - imported by PIL.ImageTk (conditional)
missing module named 'PySide.QtCore' - imported by PIL.ImageQt (conditional, optional)
missing module named 'PyQt4.QtCore' - imported by PIL.ImageQt (conditional, optional)
missing module named 'PySide2.QtCore' - imported by PIL.ImageQt (conditional, optional)
missing module named pathlib2 - imported by PIL.Image (optional)
missing module named cffi - imported by PIL.Image (optional), PIL.PyAccess (top-level), win32ctypes.core (optional), PIL.ImageTk (delayed, conditional, optional)

Solution

You can try to solve this problem by installing older versions of the matplotlib package.
eg:

pip install matplotlib==3.2.2

Answered By — hy z

Pyinstaller + PyQt + Matplotlib error

I’m tryng to generate the executable of a python code using matplotlib and pyqt that I made.
I could sucessfuly generate the executable using pyinstaller, without erros. I’m also able to execute it in my own pc, where I create the executable. But when I try to run it in another pc I get this error:

Code:

[alunos@localhost Main]$ ./Main
/home/patricia/Downloads/pyinstaller-1.4/Main/build/pyi.linux2/Main/outPYZ1.pyz/matplotlib:574: UserWarning: Could not find matplotlibrc; using defaults
/home/patricia/Downloads/pyinstaller-1.4/Main/build/pyi.linux2/Main/outPYZ1.pyz/matplotlib:635: UserWarning: could not find rc file; returning defaults
Traceback (most recent call last):
  File "<string>", line 3, in <module>
  File "/home/patricia/Downloads/pyinstaller-1.4/iu.py", line 436, in importHook
  File "/home/patricia/Downloads/pyinstaller-1.4/iu.py", line 521, in doimport
  File "/home/patricia/Downloads/pyinstaller-1.4/Main/build/pyi.linux2/Main/outPYZ1.pyz/Codigo", line 4, in <module>
  File "/home/patricia/Downloads/pyinstaller-1.4/iu.py", line 436, in importHook
  File "/home/patricia/Downloads/pyinstaller-1.4/iu.py", line 521, in doimport
  File "/home/patricia/Downloads/pyinstaller-1.4/Main/build/pyi.linux2/Main/outPYZ1.pyz/Grafico", line 2, in <module>
  File "/home/patricia/Downloads/pyinstaller-1.4/iu.py", line 436, in importHook
  File "/home/patricia/Downloads/pyinstaller-1.4/iu.py", line 521, in doimport
  File "/home/patricia/Downloads/pyinstaller-1.4/Main/build/pyi.linux2/Main/outPYZ1.pyz/matplotlib.backends.backend_qt4agg", line 9, in <module>
  File "/home/patricia/Downloads/pyinstaller-1.4/iu.py", line 436, in importHook
  File "/home/patricia/Downloads/pyinstaller-1.4/iu.py", line 521, in doimport
  File "/home/patricia/Downloads/pyinstaller-1.4/Main/build/pyi.linux2/Main/outPYZ1.pyz/matplotlib.figure", line 19, in <module>
  File "/home/patricia/Downloads/pyinstaller-1.4/iu.py", line 436, in importHook
  File "/home/patricia/Downloads/pyinstaller-1.4/iu.py", line 521, in doimport
  File "/home/patricia/Downloads/pyinstaller-1.4/Main/build/pyi.linux2/Main/outPYZ1.pyz/matplotlib.axes", line 12, in <module>
  File "/home/patricia/Downloads/pyinstaller-1.4/iu.py", line 436, in importHook
  File "/home/patricia/Downloads/pyinstaller-1.4/iu.py", line 521, in doimport
  File "/home/patricia/Downloads/pyinstaller-1.4/Main/build/pyi.linux2/Main/outPYZ1.pyz/matplotlib.axis", line 10, in <module>
  File "/home/patricia/Downloads/pyinstaller-1.4/iu.py", line 436, in importHook
  File "/home/patricia/Downloads/pyinstaller-1.4/iu.py", line 521, in doimport
  File "/home/patricia/Downloads/pyinstaller-1.4/Main/build/pyi.linux2/Main/outPYZ1.pyz/matplotlib.font_manager", line 1301, in <module>
  File "/home/patricia/Downloads/pyinstaller-1.4/Main/build/pyi.linux2/Main/outPYZ1.pyz/matplotlib.font_manager", line 1292, in _rebuild
  File "/home/patricia/Downloads/pyinstaller-1.4/Main/build/pyi.linux2/Main/outPYZ1.pyz/matplotlib.font_manager", line 967, in __init__
  File "/home/patricia/Downloads/pyinstaller-1.4/Main/build/pyi.linux2/Main/outPYZ1.pyz/posixpath", line 67, in join
AttributeError: 'NoneType' object has no attribute 'endswith'

I dont know if I made it right, I just follow the instructons in READ ME file without any other configurations.
The instructions in READ ME file was:

Non-Windows users should first build the bootloader:
cd source/linux
python ./Make.py
make

Everyone should:
python Configure.py
python Makespec.py /path/to/yourscript.py
python Build.py /path/to/yourscript.spec
.done.

Do I have to specify where is matplotlib? If so, how can I do this? I read something about iu.py but I was not able to use it properly.

And why does it show my own pc directory here: File «/home/patricia/Downloads/pyinstaller-1.4/ in spite of the directory of the pc I’m using (alunos, not patricia)?

I’m using pyqt4, python 2.6, ubuntu 9.10 to generate and 10.04 to run, matplotlib 0.99 and pyinstaller 1.4

Thanks in advance,
I would appreciate any help =p

Last edited by malaui; June 11th, 2010 at 12:20 AM.


Re: Pyinstaller + PyQt + Matplotlib error

python-packager.com

why do you want do to these?, make a deb


Re: Pyinstaller + PyQt + Matplotlib error

Because I didnt want to have to install the software, I just want to run it in a computer without the necessary libraries.


Re: Pyinstaller + PyQt + Matplotlib error

I generated the deb through the site you gave me, and unfortunately I got a similar error:

Traceback (most recent call last):
File «<string>», line 3, in <module>
File «/Python-Packager/Build-Server/pyinstaller-2.6/iu.py», line 436, in importHook
File «/Python-Packager/Build-Server/pyinstaller-2.6/iu.py», line 521, in doimport
File «/Python-Packager/Build-Server/application-builds/linux_deb/416/build/pyi.linux2/Pacote/outPYZ1.pyz/Codigo», line 1, in <module>
File «/Python-Packager/Build-Server/pyinstaller-2.6/iu.py», line 436, in importHook
File «/Python-Packager/Build-Server/pyinstaller-2.6/iu.py», line 495, in doimport
File «/Python-Packager/Build-Server/pyinstaller-2.6/iu.py», line 297, in getmod
File «/Python-Packager/Build-Server/pyinstaller-2.6/archive.py», line 468, in getmod
File «/Python-Packager/Build-Server/pyinstaller-2.6/iu.py», line 109, in getmod
ImportError: /lib/tls/i686/cmov/libc.so.6: version `GLIBC_2.11′ not found (required by ./libQtGui.so.4)

I dont know what to do…


Re: Pyinstaller + PyQt + Matplotlib error

Quote Originally Posted by malaui
View Post

I generated the deb through the site you gave me, and unfortunately I got a similar error:

I dont know what to do…

I’m having the exact same problem here. I can’t freeze and move around freely with this, since I keep having this problem. The workaround that I found was to install the python-matplotlib package on the target machine.

This obviously goes against the main idea of a «freezed» binary.

I know that this is an old post, but did you came by a solution in all this time?


Re: Pyinstaller + PyQt + Matplotlib error

Hi malaui and xuampy,

I experienced the same problem and the following work around worked for me. The binary version of the script looks for the file /etc/matplotlibrc. The only thing I needed to do was to copy that file from the compile machine to the destination machine. This allow the script to run but without font

But this is a step forward..

I have installed the package ttf-dejavu-core ttf-freefont ttf-lyx to make the fonts working.

Pierre-Yves


Я пытаюсь воспроизвести пример этого сообщения, чтобы сгенерировать исполняемый файл с помощью pyinstaller, но без успеха. Я нахожусь в операционной системе Linux.

exe, который я пытаюсь построить, основан на этом коде (test.py впоследствии)

from pylab import *
from matplotlib import pyplot as plt

figure(1, figsize=(6,6))
ax = axes([0.1, 0.1, 0.8, 0.8])

labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
explode=(0, 0.05, 0, 0)

pie(fracs, explode=explode, labels=labels,
                autopct='%1.1f%%', startangle=90)

title('Pie Chart Example', bbox={'facecolor':'0.8', 'pad':5})

show()

Чтобы создать исполняемый файл, запустите

pyinstaller --onefile test.py

Я пробовал с версией 3.0 (официальная версия в установке pip) и версия 3.1.dev из pyinstaller. Оба компилируются, но когда я запускаю исполняемый файл, я получил

./test 
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/PyInstaller/loader/pyimod03_importers.py", line 363, in load_module
    exec(bytecode, module.__dict__)
  File "/usr/share/pyshared/pylab.py", line 1, in <module>
    from matplotlib.pylab import *
  File "/usr/local/lib/python2.7/dist-packages/PyInstaller/loader/pyimod03_importers.py", line 363, in load_module
    exec(bytecode, module.__dict__)
  File "/usr/share/pyshared/matplotlib/__init__.py", line 157, in <module>
    from matplotlib.compat import subprocess
ImportError: No module named compat
test returned -1

Я читал, что возможная ошибка может быть связана с моим $PYTHONPATH (см. этот пост)
но даже с чистой $PYTHONPATH environement, у меня такая же ошибка.

Также я не понимаю, почему исполняемый файл ищет файл в каталоге /usr/, когда он должен быть автономным.

Любые советы приветствуются.
Спасибо.

PS: Это результат компиляции с pyinstaller v3.0. Обратите внимание, что
чтобы заставить его работать, мне пришлось комментировать «PyQt4» и «PyQt5» в ​​файле
/usr/local/lib/python 2.7/dist-packages/PyInstaller/hooks/hook-PIL.py, как предложено в этом сообщении .

pyinstaller --onefile test.py 
22 INFO: PyInstaller: 3.0
22 INFO: Python: 2.7.6
22 INFO: Platform: Linux-3.16.0-30-generic-x86_64-with-Ubuntu-14.04-trusty
40 INFO: wrote /home/paugam/Src/stackimage/test.spec
44 INFO: UPX is not available.
45 INFO: Extending PYTHONPATH with /home/paugam/Src/stackimage
45 INFO: checking Analysis
45 INFO: Building Analysis because out00-Analysis.toc is non existent
45 INFO: Initializing module dependency graph...
46 INFO: Initializing module graph hooks...
85 INFO: running Analysis out00-Analysis.toc
102 INFO: Analyzing /home/paugam/Src/stackimage/test.py
135 INFO: Processing pre-find module path hook   distutils
6044 INFO: Processing pre-find module path hook   site
6044 INFO: site: retargeting to fake-dir '/usr/local/lib/python2.7/dist-packages/PyInstaller/fake-modules'
11904 INFO: Looking for import hooks ...
11906 INFO: Processing hook   hook-distutils.py
11906 INFO: Processing hook   hook-sysconfig.py
11906 INFO: Processing hook   hook-xml.py
11907 INFO: Processing hook   hook-PIL.py
11907 INFO: Excluding import 'FixTk'
11910 WARNING:   Removing import 'FixTk'
11910 INFO: Excluding import 'Tkinter'
11910 INFO: Excluded import 'PySide' not found
11910 INFO: Processing hook   hook-httplib.py
11911 INFO: Processing hook   hook-pydoc.py
11911 INFO: Excluding import 'Tkinter'
11911 INFO: Processing hook   hook-PyQt4.py
11912 WARNING: Hidden import 'PyQt4._qt' not found (probably old hook)
11912 INFO: Processing hook   hook-encodings.py
12264 INFO: Processing hook   hook-_tkinter.py
12327 INFO: checking Tree
12327 INFO: Building Tree because out00-Tree.toc is non existent
12327 INFO: Building Tree out00-Tree.toc
12365 INFO: checking Tree
12366 INFO: Building Tree because out01-Tree.toc is non existent
12366 INFO: Building Tree out01-Tree.toc
12380 INFO: Processing hook   hook-matplotlib.backends.py
12798 INFO:   Matplotlib backend "GTK": added
13108 INFO:   Matplotlib backend "GTKAgg": added
13420 INFO:   Matplotlib backend "GTKCairo": added
13631 INFO:   Matplotlib backend "MacOSX": ignored
    cannot import name _macosx
13893 INFO:   Matplotlib backend "Qt4Agg": added
14120 INFO:   Matplotlib backend "TkAgg": added
14246 INFO:   Matplotlib backend "WX": ignored
    No module named wx
14464 INFO:   Matplotlib backend "WXAgg": ignored
    No module named wx

** (-c:4422): WARNING **: Couldn't connect to accessibility bus: Failed to connect to socket /tmp/dbus-psXhVLD3F9: Connection refused
14809 INFO:   Matplotlib backend "GTK3Cairo": added

** (-c:4423): WARNING **: Couldn't connect to accessibility bus: Failed to connect to socket /tmp/dbus-psXhVLD3F9: Connection refused
15146 INFO:   Matplotlib backend "GTK3Agg": added
15394 INFO:   Matplotlib backend "WebAgg": added
15605 INFO:   Matplotlib backend "agg": added
15819 INFO:   Matplotlib backend "cairo": added
15942 INFO:   Matplotlib backend "emf": ignored
    No module named backend_emf
16253 INFO:   Matplotlib backend "gdk": added
16467 INFO:   Matplotlib backend "pdf": added
16754 INFO:   Matplotlib backend "pgf": added
16966 INFO:   Matplotlib backend "ps": added
17181 INFO:   Matplotlib backend "svg": added
17403 INFO:   Matplotlib backend "template": added
17844 INFO: Processing pre-safe import module hook   gi.repository.GObject
18382 INFO: Processing hook   hook-PIL.Image.py
18632 INFO: Processing hook   hook-matplotlib.py
18745 INFO: Processing hook   hook-xml.dom.domreg.py
18746 INFO: Processing hook   hook-PyQt4.QtGui.py
18904 WARNING: Hidden import 'PyQt4._qt' not found (probably old hook)
18905 INFO: Processing hook   hook-pytz.py
18905 INFO: Processing hook   hook-setuptools.py
18906 INFO: Processing hook   hook-xml.sax.py
18906 INFO: Processing hook   hook-PIL.SpiderImagePlugin.py
18906 INFO: Excluded import 'FixTk' not found
18906 INFO: Excluding import 'Tkinter'
18907 INFO: Processing hook   hook-PyQt4.QtCore.py
18939 WARNING: Hidden import 'PyQT4._qt' not found (probably old hook)
18940 INFO: Processing hook   hook-xml.dom.py
18940 INFO: Processing hook   hook-gtk.py
18941 WARNING: Hidden import 'gtkglext' not found (probably old hook)
18942 WARNING: Hidden import 'gdkgl' not found (probably old hook)
18943 WARNING: Hidden import 'gdkglext' not found (probably old hook)
18943 WARNING: Hidden import 'gtk.gdk' not found (probably old hook)
18944 WARNING: Hidden import 'gtk.gtkgl' not found (probably old hook)
18944 WARNING: Hidden import 'gtk.gtkgl._gtkgl' not found (probably old hook)
18945 WARNING: Hidden import 'gtkgl' not found (probably old hook)
19008 INFO: Processing hook   hook-gi.repository.GObject.py
19076 INFO: Processing pre-safe import module hook   gi.repository.GLib
19101 WARNING: Hidden import 'gi._gobject.option' not found (probably old hook)
19101 INFO: Processing hook   hook-gi.py
19102 WARNING: Hidden import 'gi._error' not found (probably old hook)
19102 INFO: Processing hook   hook-gi.repository.GLib.py
19216 INFO: Looking for ctypes DLLs
19261 WARNING: library rpcrt4.dll required via ctypes not found
19303 INFO: Analyzing run-time hooks ...
19318 INFO: Including run-time hook 'pyi_rth_pkgres.py'
19320 INFO: Including run-time hook 'pyi_rth__tkinter.py'
19321 INFO: Including run-time hook 'pyi_rth_gi.py'
19321 INFO: Including run-time hook 'pyi_rth_qt4plugins.py'
19323 INFO: Including run-time hook 'pyi_rth_mplconfig.py'
19324 INFO: Including run-time hook 'pyi_rth_mpldata.py'
19345 INFO: Looking for dynamic libraries
21278 INFO: Looking for eggs
21278 INFO: Python library not in binary depedencies. Doing additional searching...
21314 INFO: Using Python library /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0
21347 INFO: Warnings written to /home/paugam/Src/stackimage/build/test/warntest.txt
21354 INFO: checking PYZ
21354 INFO: Building PYZ because out00-PYZ.toc is non existent
21355 INFO: Building PYZ (ZlibArchive) /home/paugam/Src/stackimage/build/test/out00-PYZ.pyz
22059 INFO: checking PKG
22059 INFO: Building PKG because out00-PKG.toc is non existent
22059 INFO: Building PKG (CArchive) out00-PKG.pkg
40123 INFO: Bootloader /usr/local/lib/python2.7/dist-packages/PyInstaller/bootloader/Linux-64bit/run
40123 INFO: checking EXE
40123 INFO: Building EXE because out00-EXE.toc is non existent
40123 INFO: Building EXE from out00-EXE.toc
40123 INFO: Appending archive to EXE /home/paugam/Src/stackimage/dist/test
  1. Install the Visual C++ Redistributable Package (vc_redist.x64.exe or vc_redist.x86.exe depending on your Windows). You can find it here: the latest supported visual c downloads, here: vc_redist.x64 or here: vc_redist.x86, then
  2. rebuild your executable with pyinstaller.

Analysis

I had the same error in Windows 7 64-bit articles uvdos pyinstaller with Python 3.8.7:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.
C:UserswDesktop1dist>MyTool.exe
Traceback (most recent call last):
  File "MyTool.py", line 9, in <module>
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "PyInstallerloaderpyimod03_importers.py", line 531, in exec_module
  File "matplotlib__init__.py", line 913, in <module>
  File "matplotlib__init__.py", line 812, in _rc_params_in_file
  File "contextlib.py", line 113, in __enter__
  File "matplotlib__init__.py", line 790, in _open_file_or_url
FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\w\AppData\Local\Temp\_MEI17002\matplotlib\mpl-data\matplotlibrc'
[916] Failed to execute script MyTool

I rebuilt the executable with debug articles uvdos pyinstaller level as per pyinstaller-python:

pyinstaller --onefile --log-level=DEBUG MyTool.py

In the building traces I saw the articles uvdos pyinstaller matplotlib Traceback below:

18885 INFO: Loading module hook 'hook-matplotlib.backends.py' from 'c:\users\w\appdata\local\programs\python\python38\lib\site-packages\PyInstaller\hooks'...
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "c:userswappdatalocalprogramspythonpython38libsite-packagesmatplotlib__init__.py", line 174, in <module>
    _check_versions()
  File "c:userswappdatalocalprogramspythonpython38libsite-packagesmatplotlib__init__.py", line 159, in _check_versions
    from . import ft2font
ImportError: DLL load failed while importing ft2font: The specified module could not be found.
19108 INFO: Loading module hook 'hook-matplotlib.py' from 'c:\users\w\appdata\local\programs\python\python38\lib\site-packages\PyInstaller\hooks'...
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "c:userswappdatalocalprogramspythonpython38libsite-packagesmatplotlib__init__.py", line 174, in <module>
    _check_versions()
  File "c:userswappdatalocalprogramspythonpython38libsite-packagesmatplotlib__init__.py", line 159, in _check_versions
    from . import ft2font
ImportError: DLL load failed while importing ft2font: The specified module could not be found.

That led me to: dll load failed while articles uvdos pyinstaller importing ft2font, matplotlib cant load articles uvdos pyinstaller ft2font and matplotlib import ft2font. articles uvdos pyinstaller There were several answers there which articles uvdos pyinstaller suggested installing Visual C++ articles uvdos pyinstaller Redistributable Package, and that was articles uvdos pyinstaller actually the only thing that helped.

While trying to create an .exe with matplotlib imported I get the following error:

Traceback (most recent call last): File «», line 1, in
File
«C:UsersFloAppDataLocalProgramsPythonPython38Libsite-packagesmatplotlib__init__.py»,
line 1015, in
rcParams = rc_params() File «C:UsersFloAppDataLocalProgramsPythonPython38Libsite-packagesmatplotlib__init__.py»,
line 878, in rc_params
return rc_params_from_file(matplotlib_fname(), fail_on_error) File
«C:UsersFloAppDataLocalProgramsPythonPython38Libsite-packagesmatplotlib__init__.py»,
line 731, in matplotlib_fname
for fname in gen_candidates(): File «C:UsersFloAppDataLocalProgramsPythonPython38Libsite-packagesmatplotlib__init__.py»,
line 728, in gen_candidates
yield os.path.join(get_configdir(), ‘matplotlibrc’) File «C:UsersFloAppDataLocalProgramsPythonPython38Libsite-packagesmatplotlib__init__.py»,
line 276, in wrapper
ret = func(**kwargs) File «C:UsersFloAppDataLocalProgramsPythonPython38Libsite-packagesmatplotlib__init__.py»,
line 609, in get_configdir
return _get_config_or_cache_dir(_get_xdg_config_dir()) File «C:UsersFloAppDataLocalProgramsPythonPython38Libsite-packagesmatplotlib__init__.py»,
line 562, in _get_xdg_config_dir
return os.environ.get(‘XDG_CONFIG_HOME’) or str(Path.home() / «.config») AttributeError: type object ‘Path’ has no attribute ‘home’
Traceback (most recent call last): File «», line 1, in
File
«C:UsersFloAppDataLocalProgramsPythonPython38Libsite-packagesmatplotlib__init__.py»,
line 1015, in
rcParams = rc_params() File «C:UsersFloAppDataLocalProgramsPythonPython38Libsite-packagesmatplotlib__init__.py»,
line 878, in rc_params
return rc_params_from_file(matplotlib_fname(), fail_on_error) File
«C:UsersFloAppDataLocalProgramsPythonPython38Libsite-packagesmatplotlib__init__.py»,
line 731, in matplotlib_fname
for fname in gen_candidates(): File «C:UsersFloAppDataLocalProgramsPythonPython38Libsite-packagesmatplotlib__init__.py»,
line 728, in gen_candidates
yield os.path.join(get_configdir(), ‘matplotlibrc’) File «C:UsersFloAppDataLocalProgramsPythonPython38Libsite-packagesmatplotlib__init__.py»,
line 276, in wrapper
ret = func(**kwargs) File «C:UsersFloAppDataLocalProgramsPythonPython38Libsite-packagesmatplotlib__init__.py»,
line 609, in get_configdir
return _get_config_or_cache_dir(_get_xdg_config_dir()) File «C:UsersFloAppDataLocalProgramsPythonPython38Libsite-packagesmatplotlib__init__.py»,
line 562, in _get_xdg_config_dir
return os.environ.get(‘XDG_CONFIG_HOME’) or str(Path.home() / «.config») AttributeError: type object ‘Path’ has no attribute ‘home’

This is my code if it’s needed:


from PIL import Image, ImageFont, ImageDraw
import urllib.request
import win32com
from win32com.shell import shell, shellcon
from win32com.client import Dispatch
from os import mkdir, remove, path
from datetime import date, datetime
#import winshell
#-------------------------------------------------------------------------------
# Name:        Modul1
# Purpose:
#
# Author:      Flo
#
# Created:     31.03.2020
# Copyright:   (c) Flo 2020
# Licence:     <your licence>
#-------------------------------------------------------------------------------
from datetime import date, datetime
import urllib.request
import zipfile
from shutil import copyfile, rmtree
import csv
import matplotlib.pyplot as plt
import time
start = time.time()
#-------------------------------------------------------------------------------
def datumedit(index, datumls, indexhinzufügen):
    ind = datumls.index(".")
    if ind != index:
        datumls.insert(indexhinzufügen, "0")
        ind += 1
    datumls[ind] = "-"
    return datumls
#-------------------------------------------------------------------------------
def csvdelim(liste, max):
    i = 0
    while i != max:
        ind = liste.index(";")
        liste[ind] = "-"
        i += 1
    retour = liste.index(";")
    return retour
#-------------------------------------------------------------------------------
def getvalues(file_dir,liste,liste2,ersetzenbis,floatconvertieren=False):
    durchlauf2 = 0
    keinedateninzeile = []
    with open(file_dir, newline='') as file1:
        anzahlreihen = sum(1 for line in file1)
    with open(file_dir, newline='') as file:
        reader = csv.reader(file)
        next(reader)
        for row in reader:
            durchlauf1 = 0
            uhrzeit = ""
            listed = ""
            reihe = list(str(row))
            ind = csvdelim(reihe,ersetzenbis)
            reihe[ind] = "-"
            ind1 = reihe.index(";")
            ind2 = ind+1
            inddif = ind1-ind-1
            while durchlauf1 != inddif:
                listed = listed+reihe[ind2]
                ind2 += 1
                durchlauf1 +=1
            if listed == "":
                continue
            if floatconvertieren == True:
                if listed == "":
                    None
                else:
                    liste.append(float(listed))
            else:
                liste.append(listed)

            if durchlauf2 == anzahlreihen:
                break
            indexuhzt = reihe.index(" ")
            uhrzeit = reihe[indexuhzt+1]+reihe[indexuhzt+2]+reihe[indexuhzt+3]+reihe[indexuhzt+4]+reihe[indexuhzt+5]
            liste2.append(uhrzeit)
            durchlauf2 += 1
    return liste, liste2
#-------------------------------------------------------------------------------

#-------------------------------------------------------------------------------
def bestimmtertag(datumin,orte,namen,temppath,bilderpfad,aktuellermonat,aktuellesjar,tag,monat,jahr):
    datumls = list(datumin)
    temp = temppath
    aus = False
    #CSV Herunterladen
    for e in orte:
        start1 = time.time()
        print(e)
        xpm25 = []
        xpm10 = []
        ypm25 = []
        ypm10 = []
        xpm10d = ""
        sensor = namen[e]
        if aktuellermonat == monat and jahr == aktuellesjahr:
            link = "https://www.madavi.de/sensor/data_csv/csv-files/%s-%s-%s/data-%s-%s-%s-%s.csv" %(jahr,monat,tag,sensor,jahr,monat,tag)
            iszip = False
        else:
            link = "https://www.madavi.de/sensor/data_csv/%s/%s/data-%s-%s-%s.zip" %(jahr,monat,sensor,jahr,monat)
            iszip = True
        if iszip == True:
            folderzip = "data-%s-%s-%s.zip" %(sensor,jahr,monat)
            folderohnezip = "data-%s-%s-%s" %(sensor,jahr,monat)
            filename = "data-%s-%s-%s-%s.csv" %(sensor,jahr,monat,tag)
            mkdir(temp+"\"+folderohnezip, 0o777)
            with urllib.request.urlopen(link) as dl_file:
                with open(temp+"\"+folderzip, 'wb') as out_file:
                    out_file.write(dl_file.read())
            with zipfile.ZipFile(temp+"\"+folderzip, 'r') as zip_ref:
                zip_ref.extractall(temp+"\"+folderohnezip)
            copyfile(temp+"\"+folderohnezip+"\"+filename, temp+"\"+filename)
            rmtree(temp+"\"+folderohnezip)
            remove(temp+"\"+folderzip)

        else:
            filename = "data-%s-%s-%s-%s.csv" %(sensor,jahr,monat,tag)
            with urllib.request.urlopen(link) as dl_file:
                with open(temp+"\"+filename, 'wb') as out_file:
                    out_file.write(dl_file.read())

        #CSV zu Liste
        getvalues(temp+"\"+filename,ypm10,xpm10,6,True)
        print("marker1")
        getvalues(temp+"\"+filename,ypm25,xpm25,7,True)
        remove(temp+"\"+filename)
        #Graph
        plt.style.use("dark_background")
        plt.figure(dpi=600)
        ax = plt.subplot()
        ax.yaxis.grid(True)
        print("marker2")
        plt.plot(xpm10,ypm10,"r",label="PM10",linewidth=0.7)
        plt.plot(xpm25,ypm25,"g",label="PM25",linewidth=0.7)
        ax.legend(facecolor="#cccccc")#(211,211,211,1))
        print("marker3")
        ende1 = time.time()
        plt.savefig(bilderpfad+"\"+e+".png", transparent=True)
        ende2 = time.time()
        print("marker4")
        plt.cla()
        plt.close("all")

        print('Einzelzeit: {:5.3f}s'.format(ende1-start1))
        print('Durchlauf: {:5.3f}s'.format(ende2-start1))

#-------------------------------------------------------------------------------
#
def bildtransparent(bild):
    img = Image.open(bild)
    img = img.convert("RGBA")
    datas = img.getdata()
    newData = []
    for item in datas:
        if item[0] == 255 and item[1] == 255 and item[2] == 255:
            newData.append((255, 255, 255, 0))
        else:
            newData.append(item)
    img.putdata(newData)
    img.save(bild, "PNG")
#
print("Feinstaubdaten auslesen nAutor: Florian Gruber nDatum: 25.03.2020")
namen = {"Festsaal":"esp8266-12774674","TH-Trakt":"esp8266-12775574", "Götzis":"esp8266-12775921", "Koblach":"esp8266-12776092"}
orte = ["Festsaal", "TH-Trakt", "Götzis", "Koblach"]
bilderpfad = shell.SHGetFolderPath(0, shellcon.CSIDL_MYPICTURES, None, 0)
feinbilder = bilderpfad + "\Feinstaub"
datumjetzt = datetime.now()
aktuellermonat = datumjetzt.strftime("%m")
aktuellesjahr = datumjetzt.strftime("%Y")
aktuellertag = datumjetzt.strftime("%d")
temp = feinbilder+"\temp"
j = 1
zeitraum = False
größe = (1326,756)
höheobenzusatz = 0
höheuntenzusatz = 0
breitelinkszusatz = 0
breiterechtszusatz = 0
strichliste = [0,339,678,1017,1357,1696,1357+678,2375,2714]
uhrzeiten = ["00:00","03:00","06:00","09:00","12:00","15:00","18:00","21:00","24:00"]
#Ordner erstellen
try:
    mkdir(feinbilder, 0o775)
    print("Ordner erstellt")
except:
    None
try:
    mkdir(feinbilder+"\temp", 0o777)
    print("Ordner erstellt")
except:
    None
##print(shell.SHGetFolderPath(0, shellcon.CSIDL_DESKTOP, None, 0))
##path1 = shell.SHGetFolderPath(0, shellcon.CSIDL_DESKTOP, None, 0)+"\Feinstaubdiagramme.lnk"
##desktop = winshell.desktop()
##target = path.abspath(__file__)
##shell = Dispatch('WScript.Shell')
##shortcut = shell.CreateShortCut(path1)
##shortcut.Targetpath = target
##shortcut.save()
##except:
##    print("Fehler")
#Bilder Downloaden
while True:
    datumin = "1.1.20"#input("Datum: ")
    datumls = datumedit(2, list(datumin), 0)
    datumls = datumedit(5, datumls, 3)
    if len(datumls) == 8:
        datumls.insert(-2,"2")
        datumls.insert(-2,"0")
    tag = datumls[0]+datumls[1]
    monat = datumls[3]+datumls[4]
    jahr = datumls[6]+datumls[7]+datumls[8]+datumls[9]
    datum = jahr+"-"+monat+"-"+tag
    try:
        mkdir(feinbilder+"\"+datum, 0o775)
        print("Ordner erstellt")
    except:
        None
    if aktuellertag == tag and aktuellermonat == monat and aktuellesjahr == jahr:
        tage = 0#int(input("Anzahl Tage (0 für 24h): "))

        i = 1
        links = []
        if tage == 0:
            bzeitr = "24-Stunden"
            for e in orte:
                sensor = namen[e]
                link = "https://www.madavi.de/sensor/images/sensor-%s-sds011-1-day.png" %sensor
                bild = open(feinbilder+"\"+e+".png", "wb")
                bild.write(urllib.request.urlopen(link).read())
                bild.close()
        if tage > 1:
            bzeitr = "7-Tage"
            for e in orte:
                sensor = namen[e]
                link = "https://www.madavi.de/sensor/images/sensor-%s-sds011-1-week.png" %sensor
                bild = open(feinbilder+"\"+e+".png", "wb")
                bild.write(urllib.request.urlopen(link).read())
                bild.close()
        if tage > 7:
            bzeitr = "1-Monat"
            for e in orte:
                sensor = namen[e]
                link = "https://www.madavi.de/sensor/images/sensor-%s-sds011-1-month.png" %sensor
                bild = open(feinbilder+"\"+e+".png", "wb")
                bild.write(urllib.request.urlopen(link).read())
                bild.close()
        if tage > 31:
            bzeitr = "1-Jahr"
            for e in orte:
                sensor = namen[e]
                link = "https://www.madavi.de/sensor/images/sensor-%s-sds011-1-year.png" %sensor
                bild = open(feinbilder+"\"+e+".png", "wb")
                bild.write(urllib.request.urlopen(link).read())
                bild.close()
        zeitraum = True
    else:
        bestimmtertag(datumin,orte,namen,temp,feinbilder,aktuellermonat,aktuellesjahr,tag,monat,jahr)
        größenzusatz = True
    #Collage erstellen
    if größenzusatz == True:
        größe = (7080,5600)
        höheuntenzusatz = 2300
        höheobenzusatz = -203
        breitelinkszusatz = -80
        breiterechtszusatz = 2752
    collage = Image.new("RGB",größe,(0,0,0))
    draw = ImageDraw.Draw(collage)
    for e in orte:
        if j == 1:
            tup1 = (10+breitelinkszusatz,60+höheobenzusatz) # Position Einzelbild
            tup2 = (189,35) #Position Text Orte
            tup3 = (406,2424) #Rechteck Beginn
            tup4 = (3390,2550) #Rechteck Ende
            tup5 = [541,2454,541,199] # Linien erstellen Ausgangswerte
        elif j == 2:
            tup1 = (668+breiterechtszusatz,60+höheobenzusatz)
            tup2 = (3707,35)
            tup3 = (3896,2424)
            tup4 = (6880,2550)
            tup5 = [4031,2454,3930,199]
        elif j == 3:
            tup1 = (10+breitelinkszusatz,423+höheuntenzusatz)
            tup2 = (189,2903)
            tup3 = (406,5290)
            tup4 = (3390,5416)
            tup5 = [541,5320,541,3066]
        elif j == 4:
            tup1 = (668+breiterechtszusatz,423+höheuntenzusatz)
            tup2 = (3707,2903)
            tup3 = (3896,5290)
            tup4 = (6880,5416)
            tup5 = [4031,5320,3930,3066]
        bild = Image.open(feinbilder+"\%s.png"%e)
        bild.copy()
        collage.paste(bild,tup1)
        bild.close()
        o = 0
        if größenzusatz == True:
            font = ImageFont.truetype("arial.ttf", 80)
            draw.rectangle((tup3, tup4), fill="black")
            for f in strichliste:
                if o == 9:
                    o = 0
                draw.line((tup5[0]+f,tup5[1],tup5[0]+f,tup5[3]),fill="white",width=3)#
                draw.text((tup5[0]-100+f,tup5[1]+6),uhrzeiten[o], fill="white",font=font)
                o += 1
        else:
            font = ImageFont.truetype("arial.ttf", 70)
        j += 1
        #Orte schreiben
        font = ImageFont.truetype("arial.ttf", 100)
        draw = ImageDraw.Draw(collage)
        draw.text(tup2,e,fill="white",font=font)
        draw.text((10,8),datum,(0,0,0),font=font)
        if zeitraum == True:
            draw.text((1230,8),bzeitr,(0,0,0),font=font)

    #Bild speichern
    if zeitraum == True:
        collage.save(feinbilder+"\"+datum+"\"+bzeitr+".png")
    else:
        collage.save(feinbilder+"\"+datum+"\"+datum+".png")
    #Einzelbilder löschen
    for e in orte:
        remove(feinbilder+"\"+e+".png")
    #Bild öffnen
    collage.show()
    break

Здравствуйте. Есть программа на python с использованием библиотеки PyQt5 при попытке скомпилировать ее командой pyinstaller -F -w SL_lke2.1.py вылезает ошибка:

….
18705 INFO: Loading module hook ‘hook-matplotlib.backends.py’ from ‘c:\users\iru\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\hooks’…
Traceback (most recent call last):
File “<string>”, line 1, in <module>
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesmatplotlib__init__.py”, line 822, in <module>
rcParamsDefault = _rc_params_in_file(
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesmatplotlib__init__.py”, line 727, in _rc_params_in_file
with _open_file_or_url(fname) as fd:
File “c:usersiruappdatalocalprogramspythonpython39libcontextlib.py”, line 117, in __enter__
return next(self.gen)
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesmatplotlib__init__.py”, line 701, in _open_file_or_url
fname = os.path.expanduser(fname)
File “c:usersiruappdatalocalprogramspythonpython39libntpath.py”, line 293, in expanduser
path = os.fspath(path)
TypeError: expected str, bytes or os.PathLike object, not WindowsPath
19047 INFO: Loading module hook ‘hook-matplotlib.py’ from ‘c:\users\iru\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\hooks’…
Traceback (most recent call last):
File “<string>”, line 1, in <module>
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesmatplotlib__init__.py”, line 822, in <module>
rcParamsDefault = _rc_params_in_file(
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesmatplotlib__init__.py”, line 727, in _rc_params_in_file
with _open_file_or_url(fname) as fd:
File “c:usersiruappdatalocalprogramspythonpython39libcontextlib.py”, line 117, in __enter__
return next(self.gen)
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesmatplotlib__init__.py”, line 701, in _open_file_or_url
fname = os.path.expanduser(fname)
File “c:usersiruappdatalocalprogramspythonpython39libntpath.py”, line 293, in expanduser
path = os.fspath(path)
TypeError: expected str, bytes or os.PathLike object, not WindowsPath
Traceback (most recent call last):
File “c:usersiruappdatalocalprogramspythonpython39librunpy.py”, line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File “c:usersiruappdatalocalprogramspythonpython39librunpy.py”, line 87, in _run_code
exec(code, run_globals)
File “C:UsersiruAppDataLocalProgramsPythonPython39Scriptspyinstaller.exe__main__.py”, line 7, in <module>
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesPyInstaller__main__.py”, line 126, in run
run_build(pyi_config, spec_file, **vars(args))
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesPyInstaller__main__.py”, line 65, in run_build
PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesPyInstallerbuildingbuild_main.py”, line 815, in main
build(specfile, kw.get(‘distpath’), kw.get(‘workpath’), kw.get(‘clean_build’))
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesPyInstallerbuildingbuild_main.py”, line 762, in build
exec(code, spec_namespace)
File “G:PyCharmGui_ПрограммыProgramms_PySAFTDSL_lke2.1.spec”, line 7, in <module>
a = Analysis(,
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesPyInstallerbuildingbuild_main.py”, line 294, in __init__
self.__postinit__()
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesPyInstallerbuildingdatastruct.py”, line 159, in __postinit__
self.assemble()
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesPyInstallerbuildingbuild_main.py”, line 473, in assemble
self.graph.process_post_graph_hooks(self)
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesPyInstallerdependanalysis.py”, line 373, in process_post_graph_hooks
module_hook.post_graph(analysis)
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesPyInstallerdependimphook.py”, line 451, in post_graph
self._load_hook_module()
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesPyInstallerdependimphook.py”, line 408, in _load_hook_module
self._hook_module = importlib_load_source(
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesPyInstallercompat.py”, line 632, in importlib_load_source
return mod_loader.load_module()
File “<frozen importlib._bootstrap_external>”, line 529, in _check_name_wrapper
File “<frozen importlib._bootstrap_external>”, line 1029, in load_module
File “<frozen importlib._bootstrap_external>”, line 854, in load_module
File “<frozen importlib._bootstrap>”, line 274, in _load_module_shim
File “<frozen importlib._bootstrap>”, line 711, in _load
File “<frozen importlib._bootstrap>”, line 680, in _load_unlocked
File “<frozen importlib._bootstrap_external>”, line 850, in exec_module
File “<frozen importlib._bootstrap>”, line 228, in _call_with_frames_removed
File “c:usersiruappdatalocalprogramspythonpython39libsite-packagesPyInstallerhookshook-matplotlib.py”, line 17, in <module>
assert mpl_data_dir, “Failed to determine matplotlib’s data directory!”
AssertionError: Failed to determine matplotlib’s data directory!

Как это решить? Код логики и ui на github: https://github.com/Win322/Project_SAFTD
Из тех файлов нужны только SL_lke2.1.py и UI_lke2_1.py

Отредактировано HelpMe6 (Окт. 9, 2021 12:58:40)

Понравилась статья? Поделить с друзьями:
  • Pygraphviz install error
  • Putty ошибка network error connection refused
  • Pygame как изменить размер картинки
  • Pygame error video system not initialized как исправить
  • Putty выдает ошибку network error connection refused