欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

linux 服务器没有GUI时使用matplotlib库,否则报错_tkinter.TclError: couldn't connect to display "localhost:32.0"

程序员文章站 2022-04-28 20:09:27
...

【时间】2019.08.07

【题目】linux 服务器没有GUI时使用matplotlib库,否则报错_tkinter.TclError: couldn't connect to display "localhost:32.0"

 

【问题】linux 服务器没有GUI时使用matplotlib库时,使用了以下代码:

import matplotlib.pyplot as plt

fig1 = plt.figure()
plt.plot(range(10))
fig1.savefig('f1.png')

结果卡在了fig1 = plt.figure(),最后报错:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/pyplot.py", line 525, in figure
    **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/backend_bases.py", line 3218, in new_figure_manager
    return cls.new_figure_manager_given_figure(num, fig)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/backends/_backend_tk.py", line 1008, in new_figure_manager_given_figure
    window = Tk.Tk(className="matplotlib")
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1871, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: couldn't connect to display "localhost:32.0"
 

【解决办法】

需添加:

import matplotlib
matplotlib.use('Agg')


而且必须添加在import matplotlib.pyplot之前,否则无效

即导入库时用:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt