Pyenv Python Missing Tk for Matplotlib

Jul 28, 2020
Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure

Error

If you use

import matplotlib.pyplot as pltimport numpy as npt = np.arange(0.0, 2.0, 0.01)s = 1 + np.sin(2*np.pi*t)plt.plot(t, s)plt.title('About as simple as it gets, folks')plt.show()

you will bump into the following error

test_matplot.py:9: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
  plt.show()

If you trying using

import matplotlibmatplotlib.use('TkAgg')

you will bump into the following error

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

Solution

Installing sudo apt-get install python-tk or sudo apt-get install python3-tk will not solve this issue because you are using pyenv.

Uninstall the current python version, as you need to remake with Tk support

pyenv uninstall 3.7.8

Install Tk

sudo apt-get install tk-dev

NOTE: I am not sure if sudo apt-get install python3-tk is required or not.

Install python

pyenv install 3.7.8

Create and activate new virtualenv

pyenv virtualenv 3.7.8 PROJECTpyenv activate PROJECT
pip install matplotlibpip install numpy

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.