在Docker容器内使用matplotlib.pyplot画图在运行程序时可能报错说找不到banckend,这时需要安装tkinter,对Ubuntu和Centos,安装命令稍有差异:
apt-get install python3-tk
yum install python3-tkinter
并且需要在python代码里开头处所有的import语句之后面加上两句:
import matplotlib
matplotlib.use('TkAgg')
然后运行程序可能报下面的错误:
Traceback (most recent call last):
File "draw_graphics.py", line 9, in <module>
matplotlib.use('TkAgg')
File "/usr/local/lib64/python3.6/site-packages/matplotlib/__init__.py", line 1171, in use
plt.switch_backend(name)
File "/usr/local/lib64/python3.6/site-packages/matplotlib/pyplot.py", line 287, in switch_backend
newbackend, required_framework, current_framework))
ImportError: Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running
这是因为你的容器内没有设置DISPLAY环境变量以使用host的环境来画图,查看host下的DISPLAY变量的值,在容器内设置同样的环境变量,然后运行程序可能报类似下面的错误:
_tkinter.TclError: couldn't connect to display ":1"
在host上安装x11-xserver-utils并执行命令给外来连接授权: xhost + <ip> ,然后即可运行程序正常画图了!

本文介绍了解决Docker容器环境下使用Matplotlib进行绘图时遇到的各种问题,包括缺少Tkinter后端的安装配置、DISPLAY环境变量的设置以及解决_tkinter.TclError错误的方法。
3920

被折叠的 条评论
为什么被折叠?



