Reputation: 373
I am working on an app and I have made a UI with the qt5 creator. I have a function bound to a button.
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
When pressing this button, I get a dialog window, where I can choose a file.
Also, I have a function, that should process the chosen file. Right now, the path to file and its name are hardcoded.
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'])
What I want, is to get the output of a selectFile()
function (triggered by the click)
(for example: /Users/Graygood/Desktop/Science comput/Application/Sheet.xlsx)
and insert it into process()
function (also triggered by the click), without triggering the dialog window again. Which happens if I just call selectFile()
function in process()
one.
def process(self):
fileName = self.selectFile()
file_location = fileName
sample = pd.read_excel('Sheet.xlsx', sheetname ='Sheet1', index_col=None, na_values=['NA'])
Upvotes: 0
Views: 107
Reputation: 14001
All you need to do is get the open file path on button click. And call the process method on the file_path
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")
Upvotes: 1
Reputation: 254
You should use fileName as a class attribute and so store your filename to be able to keep track if you want to reuse it without passing it in all your function.
Just need to change selectFile
to:
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
and then call self.fileName
in process(self)
.
To avoid error, you should also declare it in init method : self.fileName = None
and always test if self.fileName
exists before trying to use it.
Hope this help.
Upvotes: 1