如何将QFileDialog.getOpenFileNames中的文件路径分配给可以在类外调用的变量?

2024-09-28 20:43:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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)

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


Tags: 文件函数fromimportselftitleinit文件名
1条回答
网友
1楼 · 发布于 2024-09-28 20:43:23

试试看:

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

相关问题 更多 >