Matplotlib 和 Pyplot 的导入问题 (Python / Tkinter)

Import Issue with Matplotlib and Pyplot (Python / Tkinter)

我遇到无法调用 'matplotlib' 的 'pyplot' 元素的问题。从下面的代码中,您可以看到我必须添加一个 "TkAgg" 才能使 mattplotlib 元素正常工作,这是一个常见问题。

import matplotlib
matplotlib.use("TkAgg")

但是,现在我无法将“.pyplot”添加到导入中。我试过以下方法:

import matplotlib.pyplot as plt
plt.use("TkAgg")

但这给了我错误:

AttributeError: module 'matplotlib.pyplot' has no attribute 'use'

我该如何解决这个问题,因为我的代码需要 pyplot 才能运行,但我不知道如何导入它,同时仍然必须使用 ".use("TkAgg")。

我是 运行 Python 3.6.2,我正在使用 Tkinter 开发我的程序

这是完全不同的两件事。您导入 matplotlib 以便能够设置后端。然后你仍然需要导入 pyplot 才能在之后使用它。

import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
# ... rest of code

如果您使用 use() 函数,则必须在导入之前完成此操作 matplotlib.pyplot。导入pyplot后调用use()不会有任何效果。

import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt

检查:

matplotlib.get_backend()