Search code examples
pythonherokumatplotlibtkinter

import matplotlib failing on Heroku


[(Basically identical to this from a few months ago: https://stackoverflow.com/questions/41319082/import-matplotlib-failing-with-no-module-named-tkinter-on-heroku . However, the only solution provided doesn't seem to work. (Unfortunately I can't comment on the answer given there since I don't have enough StackOverflow reputation.))]

I've been plotting using matplotlib in my app. Everything works fine locally. However when I push my app to Heroku I get the error:

import _tkinter # If this fails your Python may not be configured for Tk
ImportError: No module named _tkinter

I've tried to circumvent Tkinter by doing:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt, mpld3

However this still throws the same error.

Has anyone found a solution for this or have a Heroku app with matplotlib that is working? I'm running Python 2.7.13 (that's also the version Heroku installs when pushing the app).

[Addition as autobot claims this is a duplicate question which it is not: Note that this question is specifically related to using matplotlib on Heroku. Therefore, any other question unrelated to Heroku does not help in answering this question]


Solution

  • I contacted Heroku support and got the following answer:

    "The default Heroku Python build doesn't contain the libs needed for tkinter to be imported successfully. You can find a list of the underlying libraries we offer by default here: https://devcenter.heroku.com/articles/cedar-ubuntu-packages

    In cases like these, we provide the opportunity for developers to extend the platform using third party buildpacks https://devcenter.heroku.com/articles/third-party-buildpacks many of which you can browse at https://elements.heroku.com/buildpacks These can install extra packages and dependencies at deploy time.

    Please be aware that third party buildpacks are an option but the buildpacks themselves are unsupported. They might not be maintained by the original authors and have stopped working. If that's the case, you'll need to contact the original author to see if they can help. There's some suggestion on this SO post that other users have used custom Python buildpacks to run this successfully https://stackoverflow.com/a/18184536

    Another option might be to use the experimental Apt buildpack here: https://github.com/heroku/heroku-buildpack-apt You would need to run

    heroku buildpacks:add --index 1 https://github.com/heroku/heroku-buildpack-apt
    

    You would also need to add a file named Aptfile at the root of the project with the following contents:

    python3-tk
    

    Unfortunately, this Aptfile doesn't have the same dependency resolution so you will have to specify any other packages manually."

    I installed the following buildpack: https://github.com/thenovices/heroku-buildpack-scipy. Which solved the issues with matplotlib.