名称错误:名称“QFileDialog”未定义

Sir*_*asm 4 python pyqt qfiledialog

我正在学习计算机科学课程,无法弄清楚为什么这段代码不起作用。我正在尝试连接一个在 PyQt4 中创建的按钮,以便当按下它时它会显示一个目录对话框:

self.Browse_Button_1 = QtGui.QToolButton(self.tab)
    self.Browse_Button_1.setGeometry(QtCore.QRect(360, 30, 61, 20))
    self.Browse_Button_1.setObjectName(_fromUtf8("Browse_Button_1"))
    file = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
    self.Browse_Button_1.clicked.connect(self, file)
Run Code Online (Sandbox Code Playgroud)

然而,每次我运行该程序时,我都会收到此错误:

Traceback (most recent call last):
   File "D:\NEA Project\NEA_UI.py", line 194, in <module>
     ui = Ui_Dialog()
   File "D:\NEA Project\NEA_UI.py", line 30, in __init__
     self.setupUi(self)
   File "D:\NEA Project\NEA_UI.py", line 55, in setupUi
     file = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
NameError: name 'QFileDialog' is not defined
Run Code Online (Sandbox Code Playgroud)

任何有关该问题的帮助将不胜感激。

mfi*_*tzp 7

QFileDialog位于QtGui 模块中,因此您需要将其附加到行的开头,例如:

file = str(QtGui.QFileDialog.getExistingDirectory(self, "Select Directory"))
Run Code Online (Sandbox Code Playgroud)

QFileDialog或者,如果您想在前面不使用QtGui,则需要从模块(在文件顶部)导入它,方法是:

from PyQt4.QtGui import QFileDialog
Run Code Online (Sandbox Code Playgroud)

或者对于 Qt5(注意在 Qt5 中,QFileDialog移至QtWidgets模块):

from PyQt5.QtWidgets import QFileDialog
Run Code Online (Sandbox Code Playgroud)