重启电脑后脚本报错AttributeError: 'QDialog'对象无'QFileDialog'属性求解决
Hey there! Let's break down what's causing this error and fix it step by step.
The Root Cause
You're trying to call Dialog.QFileDialog.getOpenFileNames() where Dialog is an instance of QDialog. But here's the key point: QFileDialog is a standalone class from PyQt/PySide, not an attribute of a QDialog object. That's exactly why Python is throwing that AttributeError at you.
Quick Fixes
First, make sure you've imported QFileDialog correctly at the top of your script. Depending on your Qt library version, it'll look like one of these:
# For PyQt5 from PyQt5.QtWidgets import QDialog, QFileDialog # For PyQt6 from PyQt6.QtWidgets import QDialog, QFileDialog # For PySide2/PySide6 from PySide2.QtWidgets import QDialog, QFileDialog # or PySide6 equivalent
Then, update your pushButton_handler method to use the QFileDialog class directly (not through your Dialog instance). Also, there's a small bug in your code: getOpenFileNames returns a tuple (list of selected files, selected filter), so you need to unpack it properly. Plus, you have duplicate pushButton_handler definitions—remove the duplicate one to avoid unexpected behavior.
Corrected Code
def pushButton_handler(self): print("Button pressed") # Call QFileDialog directly, not via your Dialog instance selected_files, selected_filter = QFileDialog.getOpenFileNames( self, "Open Data File", "", "CSV data files (*.csv)" ) # Only proceed if the user selected at least one file (avoids errors from canceling) if selected_files: # If you just need the first selected file first_file = selected_files[0] self.pathLE.setText(first_file) df = pd.read_csv(first_file) print(df) # If you need to handle multiple files, loop through the list instead # for file_path in selected_files: # df = pd.read_csv(file_path) # print(df)
Extra Notes
- If you're using PyQt6, the method signature for
getOpenFileNamesuses keyword arguments more explicitly, but the core logic of calling the class directly remains the same. - Always add a check for selected files before processing—this prevents crashes if the user clicks "Cancel" in the file dialog.
内容的提问来源于stack exchange,提问作者Dean

