【问题标题】:vscode dev container python interactive (`tkagg`) plotsvscode 开发容器 python 交互式(`tkagg`)图
【发布时间】:2022-08-16 22:45:37
【问题描述】:

预期行为(本地环境:全新 MacOS 12.4 安装)

除了$ pip3 install matplotlib,没有任何环境更新,我可以成功运行this simple plot from the Matplotlib documentation

示例代码:
# testplot.py
import matplotlib.pyplot as plt
import numpy as np

# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

fig, ax = plt.subplots()
ax.plot(t, s)

ax.set(xlabel=\'time (s)\', ylabel=\'voltage (mV)\',
       title=\'About as simple as it gets, folks\')
ax.grid()

fig.savefig(\"test.png\")
plt.show()
实际输出(窗口打开后保存为 .png):

在终端中运行$ python3 testplot.py

观察到的行为(vscode python 3.8 开发容器)

免责声明:这篇文章不涉及基于笔记本的绘图(效果很好,但并不总是首选)

但是,当我在我的开发容器中运行它时,我收到以下错误:

testplot.py:16: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
  plt.show()

第一次尝试的解决方案:

this previously posted solution 之后,我在运行解释器之前指定了后端(export MPLBACKEND=TKAgg),但错误仍然存​​在。

第二次尝试的解决方案:

在 cmets 之后,我在脚本中添加了以下几行:

import matplotlib
matplotlib.use(\'tkagg\')

在 v3.8 开发容器中,此添加将错误更改为:

Traceback (most recent call last):
  File \"testplot.py\", line 5, in <module>
    matplotlib.use(\'tkagg\')
  File \"/usr/local/python/lib/python3.8/site-packages/matplotlib/__init__.py\", line 1144, in use
    plt.switch_backend(name)
  File \"/usr/local/python/lib/python3.8/site-packages/matplotlib/pyplot.py\", line 296, in switch_backend
    raise ImportError(
ImportError: Cannot load backend \'TkAgg\' which requires the \'tk\' interactive framework, as \'headless\' is currently running

注意:添加这两行也会破坏本地脚本。本地示例的重点是表明它无需安装除 matplotlib 之外的任何东西即可绘制内容。

  • 你试过matplotlib.use(...)吗?
  • 谢谢@PaulH,我已将该案例添加到尝试的解决方案中
  • 好的——那么你对那个错误信息的解释是什么?
  • 我的第一反应是运行pip freeze 并检查是否安装了tk,并通过以下列表确认它是:tk==0.1.0。除此之外,我只是用谷歌搜索了“tk vs headless python”,并没有发现任何有用的东西。
  • 如果你在一个容器中运行——没有可以与之交互的 GUI 框架(head),对吗?

标签: docker matplotlib tkinter visual-studio-code vscode-devcontainer


【解决方案1】:

对于 Windows 机器,请参阅此答案:stackoverflow.com/a/73375874/6274417

(也许它也可以帮助你)

【讨论】:

    猜你喜欢
    • 2019-10-27
    • 2022-10-18
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多