簡體   English   中英

將數據從一種功能傳遞到另一種功能。 蟒蛇

[英]Passing data from one fucntion to another. Python

我正在開發一個應用程序,並且已經與qt5創建者創建了一個UI。 我有綁定到按鈕的功能。

self.dataChooseBtn.clicked.connect(self.selectFile)
self.data_processing.clicked.connect(self.process)

def selectFile(self):    
    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    fileName, _ = QFileDialog.getOpenFileName(self,"Выберите стандартизированную выборку", "","All Files (*);;Python Files (*.py)", options=options)
    if fileName:
        print(fileName)
        return fileName

按下此按鈕時,會出現一個對話框,在其中可以選擇一個文件。

另外,我有一個功能,應該處理所選的文件。 現在,文件的路徑及其名稱已被硬編碼。

def process(self):
    file_location = "/Users/Graygood/Desktop/Science\ comput/Application/Sheet.xlsx"
    sample = pd.read_excel('Sheet.xlsx', sheetname ='Sheet1', index_col=None, na_values=['NA'])

我想要的是獲取selectFile()函數的輸出(通過單擊觸發)(例如:/ Users / Graygood / Desktop / Science comput / Application / Sheet.xlsx),並將其插入到process()函數中(也可以通過點擊觸發),而無需再次觸發對話框窗口。 如果僅在process()調用selectFile()函數,就會發生這種情況。

def process(self):
    fileName = self.selectFile()
    file_location = fileName
    sample = pd.read_excel('Sheet.xlsx', sheetname ='Sheet1', index_col=None, na_values=['NA'])

您需要做的就是單擊按鈕獲得打開的文件路徑。 並在file_path上調用process方法

def selectFile(self):    
    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    # read the file path
    file_path, _ = QFileDialog.getOpenFileName(self,"Выберите стандартизированную выборку", "","All Files (*);;Python Files (*.py)", options=options)
    if file_path:
        # print the file_path and call process on it.
        print(file_path)
        self.process(file_path)
        return file_path

def process(self, file_path):
    # read the file at path and process it
    sample = pd.read_excel(file_path, sheetname ='Sheet1', index_col=None, na_values=['NA'])
    print("processed")

您應該將fileName用作類屬性,並存儲文件名,以便在不重用所有功能的情況下重用它時可以跟蹤。

只需將selectFile更改為:

def selectFile(self):    
    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    fileName, _ = QFileDialog.getOpenFileName(self,"Выберите стандартизированную выборку", "","All Files (*);;Python Files (*.py)", options=options)
    if fileName:
        print(fileName)
        self.fileName = fileName

然后在process(self)調用self.fileName

為了避免錯誤,您還應該在init方法中聲明它: self.fileName = None並始終在嘗試使用self.fileName之前對其進行測試。

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM