在虚拟环境使用matplotlib报错两例:
_tkinter.TclError: Can’t find a usable init.tcl in the following directories:
解决方法:
首先,退出虚拟环境:deactivate
.
然后输入pip3 -V
,查看当前系统默认的python3的lib目录:
jmh@ubuntu:~$ pip3 -V
pip 21.0.1 from /root/anaconda3/lib/python3.6/site-packages/pip (python 3.6)
可以知道是/root/anaconda3/lib/是包含python3的目录,我们进入这个目录,看到存在TK和TCL的目录:
jmh@ubuntu:/root/anaconda3/lib$ ls t
tcl8/ tcl8.5/ tclConfig.sh terminfo/ tk8.5/ tkConfig.sh
于是在自己的虚拟环境的activate文件(就是启动虚拟环境的那个给source的activate文件)追加如下环境变量:
TCL_LIBRARY="/root/anaconda3/lib/tcl8.5"
TK_LIBRARY="/root/anaconda3/lib/tk8.5"
export TCL_LIBRARY TK_LIBRARY
_tkinter.TclError: couldn’t connect to display “localhost:18.0”
原因: 在shell里面使用了交互式绘图,但是shell又没有启动x-server
解决方法:
在import matplotlib的时候变换一下方式。
原来的导入方式:
import matplotlib.pylab as plt
现在的导入方式:
import matplotlib
matplotlib.use('pdf')
import matplotlib.pylab as plt