如何将pandas数据框从主类传递到另一个类?



原始代码中有很多小部件,这就是为什么我需要在主窗口中打开文件的原因。因此,我需要将来自主菜单(主类)中打开的csv文件的数据框(data_df)传递给"MyApp"类。我将使用数据帧(input_df)来执行计算。

如何将数据从主类传递到MyApp类?

# Import dependencies
from PyQt5.QtWidgets import (QWidget, QApplication, QTableWidget, QTableWidgetItem, QHBoxLayout, QVBoxLayout, QHeaderView, QPushButton, QCheckBox,
QLabel, QFileDialog, QMainWindow, QAction, QLineEdit, QMessageBox, QComboBox, QSizePolicy)
from PyQt5.Qt import Qt, QPen, QFont
from PyQt5.QtGui import *
from PyQt5.QtChart import QChart, QChartView, QLineSeries, QCategoryAxis
import sys
import pandas as pd
import math
import csv
# Creates a QApplication instance
class MyApp(QWidget):
def __init__(self):
super().__init__()

# Creates layout object 
self.layout = QHBoxLayout()

# Create push buttons
self.buttonCalc = QPushButton('Calculate')

self.layout.addWidget(self.buttonCalc)

# Connect button to  function
self.buttonCalc.clicked.connect(self.calculate)
def displayInfo(self):
self.show()

#  Create a Model to handle the calculator's operation
def calculate(self):
# get dataframe
input_df = df 


# Create a subclass of QMainWindow to setup the main GUI
class MainWindow(QMainWindow):
def __init__(self, w):
super().__init__()
self.setWindowTitle('My code')
# for icon, uncomment line below
#self.setWindowIcon(QIcon(r'c:image.png'))
self.resize(1200, 1200)
self.myApp = MyApp()
self.menuBar = self.menuBar()
self.fileMenu = self.menuBar.addMenu('File')
# import data
importAction = QAction('Open csv File', self)
importAction.setShortcut('Ctrl+O')
importAction.triggered.connect(self.openSeries)
# exit action
exitAction = QAction('Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(lambda: app.quit())
self.fileMenu.addAction(importAction)
self.fileMenu.addAction(exitAction)
self.setCentralWidget(w)
def openSeries(self):
self.filePath = QFileDialog.getOpenFileName(self, 'Open data series csv file', 'C:', 'CSV(*.csv)')
if self.filePath != ('', ''):
file_data = self.filePath[0]
data_df = pd.read_csv(file_data, encoding='ISO-8859-1')
# I need to pass this dataframe to MyApp class
return data_df  
def passInformation(self):
self.myApp.input_df

if __name__ =='__main__':

app = QApplication(sys.argv)
w = MyApp()
window = MainWindow(w)
window.show()

try:
sys.exit(app.exec())
except SystemExit:
print('Closing window...')

你可以在你的主窗口类中使用像这样的东西通过__init__方法传递彼此的数据:

class MainWindow(QtWidgets.QWidget):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.init_ui()
def goToOtherWindow(self, variable):
self.window = OtherWindow(variable)
self.window.show()
self.close()

OnOtherWindowclass:

class OtherWindow(QtWidgets.QWidget):
def __init__(self, variable, parent=None):
super(OtherWindow, self).__init__(parent)
self.variable = variable
self.init_ui()

当然,您必须根据具体情况调整此函数。

相关内容

最新更新