问题与处理策略
1、问题描述
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.show()
- 执行上述代码,报如下错误
AttributeError: module 'backend_interagg' has no attribute 'FigureCanvas'. Did you mean: 'FigureCanvasAgg'?
# 翻译
AttributeError:模块 backend_interagg 没有属性 FigureCanvas
2、问题原因
- 这个错误与 Matplotlib 的后端(backend)配置有关,Matplotlib 的后端负责渲染图表
3、处理策略
- 在代码中显式设置 Matplotlib 后端为 TkAgg 或其他可用的后端
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('TkAgg')
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.show()
学习补充
1、Matplotlib 的一些后端
-
TkAgg:基于 Tkinter 的后端,适合大多数桌面环境
-
Qt5Agg:基于 Qt5 的后端
-
Agg:非交互式后端,适合保存图像文件
2、AttributeError
(1)基本介绍
-
AttributeError 是 Python 中的一个标准异常类型
-
AttributeError 通常在尝试访问一个对象的属性或方法时,但该对象并没有这个属性或方法时引发
(2)演示
class Student:
def __init__(self, name):
self.name = name
def sayHello(self):
print(f"Hello, {self.name}")
stu = Student("Tom")
stu.sayHello()
stu.sayOk()
- 输出结果
AttributeError: 'Student' object has no attribute 'sayOk'