Matplotlib Qt5Agg 后端未找到。

5
我编写了一个Python 3.6程序,它读取UTM坐标的.txt文件,并将其排序为逆时针顺序,使用matplotlib在图形上显示坐标,然后将坐标写入桌面上的.txt文件。当我在我一直在使用的IDE spyder中运行它时,它可以正常工作,但是当我使用cx_Freeze(通过构建我的python文件)将其转换为exe并尝试运行它时,会出现以下错误: ModuleNotFoundError: No module named 'matplotlib.backends.backend_qt5agg' 我已经尝试安装Qt5后端,方法如下: pip install PyQt5 以及更新cx_Freeze。非常感谢任何帮助。我仍然是Python和编程的初学者,所以如果我的解释不清楚,我很抱歉。以下是我的主要Python脚本的代码:
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
import math as math
import tkinter as tk
from tkinter.filedialog import askopenfilename
import time


def findFilename():
    root = tk.Tk()
    #root.withdraw()
    filename = askopenfilename()
    root.destroy()
    return(filename)

def findSize(cnt, filename):
    #number of lines in file
    with open(filename) as f:
        for line in f:
            cnt = cnt+1;
    return cnt;

def findChar(filename):
    file = open(filename, "r")

    char = ""
    lines = file.read()

    if(lines.find(" ") == -1):
        char = ","
    else:
        char = " "

    return(char)


def inputArr(cnt, arrX, arrY, arrZ, filename, char):
    file = open(filename, "r")
    num1 = 0
    num2 = 0
    num3 = 0
    place1 = 0
    place2 = 0
    place3 = 0



    for i in range(0, cnt):
        num = file.readline()
        place1 = num.find(char)
        num1 = num[:place1]
        num = num[place1 + 1:]
        place2 = num.find(char)
        num2 = num[:place2]
        num = num[place2+1:]
        place3 = num.find(char)
        num3 = num[:place3]

        arrX.append(float(num1))
        arrY.append(float(num2))
        arrZ.append(float(num3))

    return(arrX, arrY, arrZ)

def drawPath(arrX, arrY, label, cnt):
    plt.plot(arrX, arrY, '-ok', color = 'red')

    plt.xlabel("X coordinates")
    plt.ylabel("Y coordinates")
    plt.title("Loop path")
    plt.show()


    for i in range(0,cnt):
        label.append(str(i))

    for i, txt in enumerate(label):
        plt.annotate(txt, (arrX[i], arrY[i]))


def findCenter(arrX, arrY, cnt):
    xCenter = 0
    yCenter = 0

    for i in range(0,cnt):
        xCenter += arrX[i]
        yCenter += arrY[i]


    xCenter /= cnt
    yCenter /= cnt
    return(xCenter, yCenter)

def moveToCenter(arrX, arrY, arrX1, arrY1, xCenter, yCenter, cnt):
    for i in range(0,cnt):
        arrX1.append(arrX[i] - xCenter)
        arrY1.append(arrY[i] - yCenter)

    return(arrX1, arrY1)

def calculateTheta(arrX1, arrY1, arrTheta, cnt):
    for i in range(0,cnt):
        arrTheta.append(math.atan2(arrY1[i], arrX1[i]))

  #  print(arrTheta[0])
    return(arrTheta)

def sortPoints(arrTheta, arrX, arrY, arrZ, cnt):
    minimum = 0

    for i in range(0,cnt-1):
        minimum = i
        for j in range(i + 1, cnt):
            if(arrTheta[j] < arrTheta[minimum]):
                minimum = j
        arrTheta[minimum], arrTheta[i] = arrTheta[i], arrTheta[minimum]
        arrX[minimum], arrX[i] = arrX[i], arrX[minimum]
        arrY[minimum], arrY[i] = arrY[i], arrY[minimum]
        arrZ[minimum], arrZ[i] = arrZ[i], arrZ[minimum]

def writeFile(arrX, arrY, arrZ, cnt, char):
    moment = time.strftime("%Y-%b-%d__%H_%M_%S",time.localtime())

    file = open("C:\\Users\\natha\\Desktop\\sorted" + str(moment) + ".txt", "w")
    num = ""

    for i in range(0,cnt):
        if(i < 10):
            num = "0"
        else:
            num = ""

        file.write("<" + "L" + num + str(i) + ">" + " " + str(arrX[i]) + char + 
                   str(arrY[i]) + char + str(arrZ[i]) + char + "\n")




def main():

    cnt = 0
    arrX = []
    arrY = []
    arrZ = []
    label = []
    arrX1 = []
    arrY1 = []
    arrTheta = []
    xCenter = 0
    yCenter = 0
    char = ""

    filename = findFilename()
    char = findChar(filename)

    cnt = findSize(cnt, filename)

    findChar(filename)
    inputArr(cnt, arrX, arrY, arrZ, filename, char)

    xCenter, yCenter = findCenter(arrX, arrY, cnt)
    arrX1, arrY1 = moveToCenter(arrX, arrY, arrX1, arrY1, xCenter, yCenter, cnt)

    arrTheta = calculateTheta(arrX1, arrY1, arrTheta, cnt)
    #arrX, arrY, arrZ = randomPoints(arrX, arrY, arrZ, cnt)
    sortPoints(arrTheta, arrX, arrY, arrZ, cnt)

    writeFile(arrX, arrY, arrZ, cnt, char)
    drawPath(arrX, arrY, label, cnt)


main()

除了我的setup.py文件

from cx_Freeze import setup, Executable
import sys
import os.path


os.environ['TCL_LIBRARY'] = r'C:\Users\natha\Anaconda3\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\natha\Anaconda3\tcl\tk8.6'

additional_mods = ['numpy.core._methods', 'numpy.lib.format']
setup(name='loopProgram', 
      version='0.4', 
      description='xyz script',
      options = {'build_exe': {'includes': additional_mods}},
      executables = [Executable('loopProgram.py')]
    )

1
你尝试过“TkAgg”后端吗?我不是100%确定,但“TkAgg”似乎更适合Tk应用程序。 - Kohki Mametani
5个回答

5

安装缺失的Matplotlib qt5后端: sudo apt-get install python-matplotlib-qt5

获取Matplotlib配置文件路径: python import matplotlib matplotlib.matplotlib_fname() u'/usr/lib64/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc' 在配置文件中,将后端更改为qt5agg vi /usr/lib64/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc

将行更改为:

backend: qt5agg


你好,感谢您的回复。当我打开matplotlibrc文件时,默认情况下我的后端是qt5agg。但它仍然无法正常工作。如果有帮助的话,我正在使用Windows 10操作系统。 - ralpher01
在Ubuntu20.04上出现了“E: 无法定位软件包python-matplotlib-qt5”的错误。 - Pe Dro
首先感谢@Neeraj Nair(对于任何人来说),在Fedora中这将起作用。 dnf install python3-matplotlib-qt5 - abhilash

3

对于OpenSUSE,我发现上面的答案都不起作用。 我尝试了各种后端,但没有显示任何内容。 脚本运行没有输出错误信息,而且 plot.show() 函数甚至没有阻塞控制台。plot.savefig()此主题中概述的正确使用方式一样,可以正常工作。

这个链接表明,在安装 matplotlib 之前,我需要添加 tk-devel。 使用 Zypper 安装了 tk-devel,卸载了 python3-matplotlib,重新安装 matplotlib,然后就可以正常工作了。


1

我知道这是一个旧帖子,但最近我在Spyder 5中遇到了这个问题。 我正在使用OpenSUSE,并且通过安装python38-matplotlib-qt5解决了这个问题。

zypper in python38-matplotlib-qt5

首先检查您的Python版本!!!这可能仅适用于Python3.8及以上版本。


1

你尝试过添加以下行吗

import matplotlib.backends.backend_qt5agg

在您的主要Python脚本(或任何其他适用于您的脚本的模块)中,以“强制”cx_Freeze包含此模块的方式?

1
澄清一下cx_Freeze是如何决定包含什么内容的可能会有所帮助(以及为什么在这种情况下qt5agg是一个“隐藏”的导入)。 - SNygard
@SNygard 我完全同意你的观点,但我不知道答案。在开发应用程序时,我注意到需要显式地导入import matplotlib.backends.backend_ps才能将绘图保存为冻结应用程序中的后缀文件。其他后端(如PNG)由cx_Freeze包含,无需显式导入。 - jpeg

0

我也遇到了同样的问题,尝试重新安装matplolib

pip3 uninstall matplotlib

然后

pip3 install matplotlib

这解决了我的问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接