Cannot import name _tkagg


I had Matplotlib installed on a computer. I tried to set the backend for a plot using TkAgg. There was no Tk installed, so I installed the required packages. When I tried to set backend again, I got this error: ImportError: cannot import name _tkagg


Check if your Matplotlib is installed using pip. If so, then you need to reinstall Matplotlib so that it picks up links to the python-tk files correctly:

$ sudo pip uninstall matplotlib
$ sudo pip install matplotlib

The plot was displayed correctly after this.

Tried with: Ubuntu 14.04

Matplotlib plot is not displayed in window


I created a plot using the Matplotlib library in a Python script. But the call to show does not display the plot in a GUI window.


The rendering of a plot to a file or display is controlled by the backend that is set in Matplotlib. You can check the current backend using:

import matplotlib

I got the default backend as Agg. The possible values for GUI backends on Linux are Qt4Agg, GTKAgg, WXagg, TKAgg and GTK3Agg. Since Agg is not a GUI backend, nothing is being displayed.

I wanted to use the simple Tcl-Tk backend. So, I installed the necessary packages for Python:

$ sudo apt install tcl-dev tk-dev python-tk python3-tk

The backend is not set automatically after this. In my Python script, I set it explicitly:

import matplotlib
matplotlib.rcParams["backend"] = "TkAgg"

The plot was displayed after this change.

However, this needs to be set immediately after the import line of Matplotlib and before importing matplotlib.pyplot. Doing this in the import region of a Python script is quite ugly.

Instead, I like to switch the backend of the matplotlib.pyplot object itself:

import matplotlib.pyplot as mplot

This too worked fine for me! 🙂

Reference: Matplotlib figures not showing up or displaying

Tried with: Ubuntu 14.04