简体   繁体   中英

How to choose multiple files from file dialog and open at the same time and access them

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QFileDialog
from PyQt5 import QtCore
import sys
 
 
def dialog():
    file , check = QFileDialog.getOpenFileName(None, "QFileDialog.getOpenFileName()",
                    "", "All Files (*);;Python Files (*.py);;Text Files (*.txt)")
    if check:
        print(file)
 
app = QApplication(sys.argv)
win = QMainWindow()
win.setGeometry(400,400,300,300)
win.setWindowTitle("CodersLegacy")
  
button = QPushButton(win)
button.setText("Press")
button.clicked.connect(dialog)
button.move(50,50)
 
win.show()
sys.exit(app.exec_())

Here is the code to select and open a single file when I press a button. However, how can this is changed to select multiple files and open at the same time. I tried for the syntax, unfortunately, I could not find one.

You have to use the QFileDialog::getOpenFileNames() method, also the second value of the tuple that returns is not a check but a string that indicates the filter used, if you want to verify then you have to use the size of the filenames:

filenames, _ = QFileDialog.getOpenFileNames(
    None,
    "QFileDialog.getOpenFileNames()",
    "",
    "All Files (*);;Python Files (*.py);;Text Files (*.txt)",
)
if filenames:
    for filename in filenames:
        print(filename)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM