如何在类之外调用从QFileDialog.getOpenFileNames到变量的文件路径分配?

时间:2019-08-20 12:01:09

标签: python pyqt5

我是pyqt的新手,目前正在尝试使文件对话框功能正常工作。它可以在类和函数内部打印文件名,但不能将文件名保存到函数外部的变量中。

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog
from PyQt5.QtGui import QIcon


class open_file(QWidget):

    global file_name

    def __init__(self):
        super().__init__()
        self.title = 'Select Image'
        self.left = 10
        self.top = 10
        self.width = 640
        self.height = 480
        self.initUI()

    def initUI(self):

        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.openFileNamesDialog()
        self.show()

    def openFileNamesDialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        files, _ = QFileDialog.getOpenFileNames(self, "QFileDialog.getOpenFileNames()", "",
                                                "Images (*.png *.jpg)", options=options)
        return files



names = ex.openFileNamesDialog()
print(names)

我希望选择文件后可以打印文件名,但是什么都不会打印

1 个答案:

答案 0 :(得分:1)

尝试一下:

import sys 
from PyQt5.QtWidgets  import (QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog,
                         QVBoxLayout, QLabel, QPushButton)
from PyQt5.QtGui import QIcon

class OpenFile(QWidget):
#    global file_name

    def __init__(self):
        super().__init__()
        self.title = 'Select Image'
        self.left   = 100
        self.top    = 100
        self.width  = 640
        self.height = 480

        self.initUI()

        self.label  = QLabel()
        button = QPushButton("Click me", clicked=self.openFileNamesDialog)


        vbox = QVBoxLayout(self)
        vbox.addWidget(self.label)
        vbox.addWidget(button)

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
#        self.openFileNamesDialog()

    def openFileNamesDialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        files, _ = QFileDialog.getOpenFileNames(self, "QFileDialog.getOpenFileNames()", "",
                                                "Images (*.png *.jpg)", options=options)
#        return files
        if  files:
            print(*files, sep="\n")
            self.label.setText(", \n".join(files))

#names = ex.openFileNamesDialog() print(names)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = OpenFile()
    ex.show()
    sys.exit(app.exec_()) 

enter image description here