Gangmax Blog

Fix No module named tkinter issue

This problems happens when I run Python code which uses “import matplotlib.pyplot as plt” or “import axelrod as axl”. Both of them use “tk”.

The full error:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> import matplotlib.pyplot as plt
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/gang/.pyenv/versions/3.5.3/lib/python3.5/site-packages/matplotlib/pyplot.py", line 115, in <module>
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
File "/home/gang/.pyenv/versions/3.5.3/lib/python3.5/site-packages/matplotlib/backends/init.py", line 32, in pylab_setup
globals(),locals(),[backend_name],0)
File "/home/gang/.pyenv/versions/3.5.3/lib/python3.5/site-packages/matplotlib/backends/backend_tkagg.py", line 6, in <module>
from six.moves import tkinter as Tk
File "/home/gang/.pyenv/versions/3.5.3/lib/python3.5/site-packages/six.py", line 92, in get
result = self._resolve()
File "/home/gang/.pyenv/versions/3.5.3/lib/python3.5/site-packages/six.py", line 115, in _resolve
return _import_module(self.mod)
File "/home/gang/.pyenv/versions/3.5.3/lib/python3.5/site-packages/six.py", line 82, in _import_module
import(name)
File "/home/gang/.pyenv/versions/3.5.3/lib/python3.5/tkinter/init.py", line 35, in <module>
import _tkinter # If this fails your Python may not be configured for Tk
ImportError: No module named '_tkinter'

I use “pyenv” to manage my local Python environments.

I searched a lot, most of the result said that installing “python3-tk”, “tk”, “python-tk” or “tk-dev” will fix the issue. But for my case, no. Until I found the answer here and here.

The fix is:

  1. Install “tk-dev”, for me it’s “sudo apt-get install tk-dev”;

  2. Uninstall the existing Python environment of pyenv and install it again, which will use “tk-dev” to compile Python and the missing “_tkinter” module will be compiled.

1
2
3
4
5
6
sudo apt-get install tk-dev
pip freeze > requirements.txt
pyenv uninstall 3.6.0
pyenv install 3.6.0
pyenv global 3.6.0
pip install -r requirements.txt

Done.

Comments