Python3 ImportError:在Ubuntu上没有名为'_tkinter'的模块

时间:2017-05-29 07:55:05

标签: python matplotlib tkinter

当我导入matplotlib时,当前版本的Python3是3.5.2,它重新调整了以下错误

>>> import matplotlib.pyplot as plt
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/site-packages/matplotlib/pyplot.py", line 115, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "/usr/local/lib/python3.5/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup
    globals(),locals(),[backend_name],0)
  File "/usr/local/lib/python3.5/site-packages/matplotlib/backends/backend_tkagg.py", line 6, in <module>
    from six.moves import tkinter as Tk
  File "/usr/local/lib/python3.5/site-packages/six.py", line 92, in __get__
    result = self._resolve()
  File "/usr/local/lib/python3.5/site-packages/six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "/usr/local/lib/python3.5/site-packages/six.py", line 82, in _import_module
    __import__(name)
  File "/usr/local/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'

导入tkinter

Python 3.5.2 (default, Jan 19 2017, 11:29:22)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/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'
>>>

似乎tkinter已被安装。

我已经通过

安装了tk和tcl
sudo apt-get install tk-dev
sudo apt-get install tk8.6-dev

操作系统是Ubuntu 14.04。

我认为这是在Python3上没有配置TK的原因,但我不确定。很多人说我应该用tk重建并重新安装Python3,但我不认为这是解决这个问题的一种优雅方式。

如何解决此问题?

1 个答案:

答案 0 :(得分:3)

如果您在matplotlib后端遇到问题,请尝试选择其他后端 Matplotlib适用于许多不同的场景和用途 在Linux上,我使用以下代码来选择可用的后端并首先使用。

import matplotlib
gui_env = ['TKAgg','GTKAgg','Qt4Agg','WXAgg']
for gui in gui_env:
    try:
        matplotlib.use(gui,warn=False, force=True)
        from matplotlib import pyplot as plt
        break
    except:
        continue

,如果您要创建图像文件而不是显示它

使用:

matplotlib.use('agg')
from matplotlib import pyplot as plt

编辑:
根据您的评论尝试这一点,看看您是否得到了有效的结果。

import matplotlib
gui_env = [i for i in matplotlib.rcsetup.interactive_bk]
print ("I will test for", gui_env)
for gui in gui_env:
    print ("testing", gui)
    try:
        matplotlib.use(gui,warn=False, force=True)
        from matplotlib import pyplot as plt
        print ("    ",gui, "Is Available")
        plt.plot([1.5,2.0,2.5])
        fig = plt.gcf()
        fig.suptitle(gui)
        plt.show()
        print ("Using ..... ",matplotlib.get_backend())
    except:
        print ("    ",gui, "Not found")