2017-11-21 6 views
0

PyQt5을 배우고 GUI에 Matplotlib 플롯을 표시하려고합니다. 지금은 CSV 파일에서 Menubar로드 버튼으로 데이터를로드하려고합니다. 나는 이것을 성공적으로 할 수있다. 내 문제는이 데이터를 차트에 표시하는 것입니다. 내가 나중에 일반화하는 매우 구체적인 경우를 OpenFile에서PyQt5에서 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_()) 

,하지만 난 처음 두 행이 헤더이다 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' 

를 얻을.

답변

1

QObject.connect() 함수는 호출 가능한 인수를 필요로합니다. btn.clicked.connect(plotCan.plot(self.data))를 작성 당신은 당신이 전화와 함께 self.data 변수를 전달하려는 때문에 따라서 오류 메시지가

를 받고, 그것을 (지정 없음 return 이후 기본적으로 None) plotCan.plot(self.data)에 대한 호출의 결과를 전달하는 간단한 방법이이 기능을 만족 connect()

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

람다를 사용할 수 있으며, plotCan.plot()

호출을 연기
관련 문제