Python 在PyQt5中使用Matplotlib打印CSV文件

Python 在PyQt5中使用Matplotlib打印CSV文件,python,matplotlib,pyqt,pyqt5,Python,Matplotlib,Pyqt,Pyqt5,我正在尝试学习PyQt5并在GUI上显示Matplotlib绘图。现在,我正在尝试使用我的菜单栏中的加载按钮从CSV文件加载数据。我可以成功地做到这一点。我的问题是现在在图表上显示这些数据。这是我的密码: import sys from PyQt5.QtWidgets import (QMainWindow, QAction, qApp, QApplication, QPushButton, QDesktopWidget, QLabel,

我正在尝试学习
PyQt5
并在GUI上显示
Matplotlib
绘图。现在,我正在尝试使用我的
菜单栏中的加载按钮从CSV文件加载数据。我可以成功地做到这一点。我的问题是现在在图表上显示这些数据。这是我的密码:

import sys
from PyQt5.QtWidgets import (QMainWindow, QAction, qApp, QApplication, QPushButton, QDesktopWidget,
                            QLabel, QFileDialog, QWidget, QGridLayout, QMenu, QSizePolicy, QMessageBox, QWidget)
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QCoreApplication, Qt
from win32api import GetSystemMetrics

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

import numpy as np

import random

CURRENT_VERSION = 0.1

class Example(QMainWindow):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.setWindowTitle('test')

        window_width = GetSystemMetrics(0)
        window_height = GetSystemMetrics(1)

        self.resize(0.6 * window_width, 0.6 * window_height)
        self.center()

        self.setWindowIcon(QIcon('Icon.png'))

        #inits
        self.openDirectoryDialog = ""
        self.data = np.empty(shape=(1,2), dtype=np.float)

        #Exit on menubar
        exitAct = QAction('&Exit', self)
        exitAct.setShortcut('Ctrl+Q')
        exitAct.setStatusTip('Exit applicatiion')
        exitAct.triggered.connect(qApp.quit)

        #Open on menubar
        openAct = QAction('&Open', self)
        openAct.setShortcut('Ctrl+O')
        openAct.setStatusTip('Open Directory')
        openAct.triggered.connect(self.openFile)

        #menubar
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAct)
        fileMenu.addAction(openAct)

        #Central
        centralwidget = QWidget(self)
        self.setCentralWidget(centralwidget)

        #Grid
        grid = QGridLayout(centralwidget)
        self.setLayout(grid)

        #Plot
        plotCan = PlotCanvas(self, width=5, height=4)
        grid.addWidget(plotCan , 0,1)

        #button
        btn = QPushButton("Load Data", centralwidget)
        btn.resize(btn.sizeHint())
        grid.addWidget(btn, 0,0)

        btn.clicked.connect(plotCan .plot(self.data))

        self.show()

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def openFile(self):
        self.csvFile = QFileDialog.getOpenFileName(self, "Get Dir Path")[0]
        self.data = np.loadtxt(self.csvFile, delimiter=',', dtype='S')[2:].astype(np.float)

    def buttonpress(self):
        self.plot(self.data)

class PlotCanvas(FigureCanvas):

    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.setSizePolicy(self,
                QSizePolicy.Expanding,
                QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def plot(self, data = np.empty(shape=(1,2))):
        ax = self.figure.add_subplot(111)
        ax.plot(data[:,0],data[:,1], 'r-')
        ax.set_title('PyQt Matplotlib Example')
        self.draw()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    w = Example()
    sys.exit(app.exec_())
OpenFile
中,我有一个非常具体的案例,稍后我将对其进行概括,但我使用的是一个CSV文件,其中前两行是标题。目前,当我启动程序时,我得到了错误

Traceback (most recent call last):
  File "Plotter.py", line 115, in <module>
    w = Example()
  File "Plotter.py", line 23, in __init__
    self.initUI()
  File "Plotter.py", line 75, in initUI
    btn.clicked.connect(plotCav.plot(self.data))
TypeError: argument 1 has unexpected type 'NoneType'
回溯(最近一次呼叫最后一次):
文件“Plotter.py”,第115行,在
w=示例()
文件“Plotter.py”,第23行,在_init中__
self.initUI()
initUI中第75行的文件“Plotter.py”
btn.单击.连接(plotCav.plot(self.data))
TypeError:参数1具有意外的类型“NoneType”
我不明白,因为我已经初始化了数据。

函数需要一个可调用的参数。在写入
btn.clicked.connect(plotCan.plot(self.data))
时,您将调用的结果传递给它
plotCan.plot(self.data)
None
默认情况下,因为没有指定
return
),因此您将收到错误消息

由于您希望在调用时传递
self.data
变量,因此一种简单的方法是使用lambda

btn.clicked.connect(lambda: plotCan.plot(self.data))
这满足了
connect()
函数的要求,并推迟了对
plotCan.plot()的调用