Pyenv Python Missing Tk for Matplotlib

July 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 plt
import numpy as np

t = 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 matplotlib

matplotlib.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 PROJECT
pyenv activate PROJECT
pip install matplotlib
pip install numpy
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.