_tkinter.TclError: 使用 wordcloud 时无法连接显示“localhost:10.0”

W. *_*yna 5 ubuntu python-3.x

我得到_tkinter.TclError: couldn't connect to display "localhost:10.0"SSH'ing时(含-X)到我的Ubuntu 16.04服务器,运行此脚本

from os import path
from wordcloud import WordCloud
import matplotlib as mpl
import matplotlib.pyplot as plt

mpl.use('Agg')
d = path.dirname(__file__)

text = open(path.join(d, 'words.txt')).read()
wordcloud = WordCloud().generate(text)

# Configure plot
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")

# lower max_font_size
wordcloud = WordCloud(max_font_size=40).generate(text)
plt.figure()
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")

plt.savefig("comments.png")
Run Code Online (Sandbox Code Playgroud)

此脚本使用 Wordcloud ( https://github.com/amueller/word_cloud/ )。words.txt是一堆我打算变成词云的词。应该发生的事情是云被保存为comments.png(但未显示)在我正在连接的服务器上。

man*_*bcd 9

我在通过 SSH 使用 Ubuntu 16.04 使用 Tensorflow 时遇到了同样的问题。

尝试使用 Agg 渲染引擎而不是 X11(它对我有用)。

添加以下几行就成功了

import matplotlib
matplotlib.use('Agg')
Run Code Online (Sandbox Code Playgroud)

感谢来自此线程的@Mark:在结束 ssh 会话后在后台运行 python/matplotlib 时出现问题