Open file dialog with python

PyQt QFileDialog

Summary: in this tutorial, you’ll learn how to use the PyQt QFileDialog class to create file dialogs that allow users to select files or directories from the file system.

Introduction to the PyQt QFileDialog

The QFileDialog class creates a file dialog widget that allows users to traverse the file system and select one or more files or a directory.

To create a file dialog object, you create a new instance of the QFileDialog :

dialog = QFileDialog(self)Code language: Python (python)

The QFileDialog object has the setFileMode() method that allows users to select an existing file:

dialog.setFileMode(QFileDialog.FileMode.ExistingFiles)Code language: Python (python)

or a file that does not exist:

dialog.setFileMode(QFileDialog.FileMode.AnyFile)Code language: Python (python)

This option is useful for the Save As file dialog scenario. See the QFileDialog .FileMode enum for the complete file modes.

Filtering file types

To specify which types of files users are expected to select, you can use the setNameFilter() method. For example, the following filter expects users to select only PNG and JPEG files:

dialog.setNameFilter("Images (*.png *.jpg)")Code language: Python (python)

To use multiple filters, you need to separate each with two semicolons. For example:

"Images (*.png *.jpg);;Vector (*.svg)"Code language: Python (python)

Setting views for file dialogs

The file dialog has two view modes: list and detail.

  • The list view shows the contents of the current directory as a list of files and directory names
  • The detail view displays additional information such as file sizes and modified dates.

To set the view mode, you use the setViewMode() method:

dialog.setViewMode(QFileDialog.Detail)Code language: Python (python)

Once you complete the setting, you can show the file dialog using the selectFiles() method. If the user clicks the OK button, the selected files are put in fileNames :

if dialog.exec_(): fileNames = dialog.selectedFiles()Code language: Python (python)

To set starting directory of the file dialog, you use the setDirectory() method. For example:

dialog.setDirectory('C:/images/')Code language: Python (python)

The following program uses a file dialog that allows users to select image files:

import sys from PyQt6.QtWidgets import ( QApplication, QWidget, QFileDialog, QGridLayout, QPushButton, QLabel, QListWidget ) from pathlib import Path class MainWindow(QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setWindowTitle('PyQt File Dialog') self.setGeometry(100, 100, 300, 150) layout = QGridLayout() self.setLayout(layout) # file selection file_browser_btn = QPushButton('Browse') file_browser_btn.clicked.connect(self.open_file_dialog) self.file_list = QListWidget(self) layout.addWidget(QLabel('Files:'), 0, 0) layout.addWidget(self.file_list, 1, 0) layout.addWidget(file_browser_btn, 2 ,0) self.show() def open_file_dialog(self): dialog = QFileDialog(self) dialog.setDirectory(r'C:\images') dialog.setFileMode(QFileDialog.FileMode.ExistingFiles) dialog.setNameFilter("Images (*.png *.jpg)") dialog.setViewMode(QFileDialog.ViewMode.List) if dialog.exec(): filenames = dialog.selectedFiles() if filenames: self.file_list.addItems([str(Path(filename)) for filename in filenames]) if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() sys.exit(app.exec())Code language: Python (python)

Selecting a single file using the getOpenFileName() method

It’s more concise to use the static method getOpenFileName() of the QFileDialog class to open file dialog. For example:

import sys from PyQt6.QtWidgets import QApplication, QMainWindow, QFileDialog, QWidget, QGridLayout,QLineEdit,QPushButton, QLabel from pathlib import Path class MainWindow(QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setWindowTitle('PyQt File Dialog') self.setGeometry(100, 100, 400, 100) layout = QGridLayout() self.setLayout(layout) # file selection file_browse = QPushButton('Browse') file_browse.clicked.connect(self.open_file_dialog) self.filename_edit = QLineEdit() layout.addWidget(QLabel('File:'), 0, 0) layout.addWidget(self.filename_edit, 0, 1) layout.addWidget(file_browse, 0 ,2) self.show() def open_file_dialog(self): filename, ok = QFileDialog.getOpenFileName( self, "Select a File", "D:\\icons\\avatar\\", "Images (*.png *.jpg)" ) if filename: path = Path(filename) self.filename_edit.setText(str(path)) if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() sys.exit(app.exec())Code language: Python (python)

First, create a button and connect the clicked signal with the open_file_dialog method:

file_browse = QPushButton('Browse') file_browse.clicked.connect(self.open_file_dialog)Code language: Python (python)

Second, define the open_file_dialog() method and call the getOpenFileName() static method of the QFileDialog class to open a file dialog:

def open_file_dialog(self): filename, _ = QFileDialog.getOpenFileName( self, "Select a File", r"C:\images\", "Images (*.png *.jpg)" ) if filename: path = Path(filename) self.filename_edit.setText(str(path))Code language: Python (python)

The getOpenFileName() has the title of “Select a File”, starting directory as “C:\images\”, and expects users to select a png or jpg file only.

The getOpenFileName() method returns a tuple. The first element of the tuple stores the selected file path. Since we don’t need the second element, we assign it to the _ variable.

Selecting multiple files using the getOpenFileNames() method

To allow users to select multiple files in a file dialog, you use the getOpenFileNames() method instead of the getOpenFileName() method.

The getOpenFileNames() works like the getOpenFileName() except the first element of the returned tuple contains a list of the selected files.

The following program uses the getOpenFileNames() method to allow users to select multiple files and fills a list widget with selected file names:

import sys from PyQt6.QtWidgets import QApplication, QFileDialog, QWidget, QGridLayout, QListWidget, QPushButton, QLabel from pathlib import Path class MainWindow(QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setWindowTitle('PyQt File Dialog') self.setGeometry(100, 100, 400, 100) layout = QGridLayout() self.setLayout(layout) # file selection file_browse = QPushButton('Browse') file_browse.clicked.connect(self.open_file_dialog) self.file_list = QListWidget(self) layout.addWidget(QLabel('Selected Files:'), 0, 0) layout.addWidget(self.file_list, 1, 0) layout.addWidget(file_browse, 2, 0) self.show() def open_file_dialog(self): filenames, _ = QFileDialog.getOpenFileNames( self, "Select Files", r"C:\images\", "Images (*.png *.jpg)" ) if filenames: self.file_list.addItems([str(Path(filename)) for filename in filenames]) if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() sys.exit(app.exec())Code language: Python (python)

Selecting a directory

To open a file dialog for selecting a directory, you use the getExistingDirectory() method of the QFileDialog class. For example:

import sys from PyQt6.QtWidgets import QApplication, QFileDialog, QWidget, QGridLayout, QLineEdit, QPushButton, QLabel from pathlib import Path class MainWindow(QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setWindowTitle('PyQt File Dialog') self.setGeometry(100, 100, 400, 100) layout = QGridLayout() self.setLayout(layout) # directory selection dir_btn = QPushButton('Browse') dir_btn.clicked.connect(self.open_dir_dialog) self.dir_name_edit = QLineEdit() layout.addWidget(QLabel('Directory:'), 1, 0) layout.addWidget(self.dir_name_edit, 1, 1) layout.addWidget(dir_btn, 1, 2) self.show() def open_dir_dialog(self): dir_name = QFileDialog.getExistingDirectory(self, "Select a Directory") if dir_name: path = Path(dir_name) self.dir_name_edit.setText(str(path)) if __name__ == '__main__': app = QApplication(sys.argv) window = MainWindow() sys.exit(app.exec())Code language: Python (python)

Summary

  • A file dialog allows you to select one or more files or a directory.
  • Use the QFileDialog class to create a file dialog widget.
  • Use the getOpenFileName() static method of the QFileDialog to create a file dialog that allows users to select a single file.
  • Use the getOpenFileNames() static method of the QFileDialog class to create a file dialog that allows users to select multiple files.
  • Use the getExistingDirectory() static method of the QFileDialog class to create a file dialog that allows users to select a directory.

Источник

Tkinter Dialogs¶

tkinter.simpledialog — Standard Tkinter input dialogs¶

The tkinter.simpledialog module contains convenience classes and functions for creating simple modal dialogs to get a value from the user.

tkinter.simpledialog. askfloat ( title , prompt , ** kw ) ¶ tkinter.simpledialog. askinteger ( title , prompt , ** kw ) ¶ tkinter.simpledialog. askstring ( title , prompt , ** kw ) ¶

The above three functions provide dialogs that prompt the user to enter a value of the desired type.

class tkinter.simpledialog. Dialog ( parent , title = None ) ¶

The base class for custom dialogs.

body ( master ) ¶

Override to construct the dialog’s interface and return the widget that should have initial focus.

buttonbox ( ) ¶

Default behaviour adds OK and Cancel buttons. Override for custom button layouts.

tkinter.filedialog — File selection dialogs¶

The tkinter.filedialog module provides classes and factory functions for creating file/directory selection windows.

Native Load/Save Dialogs¶

The following classes and functions provide file dialog windows that combine a native look-and-feel with configuration options to customize behaviour. The following keyword arguments are applicable to the classes and functions listed below:

Static factory functions

The below functions when called create a modal, native look-and-feel dialog, wait for the user’s selection, then return the selected value(s) or None to the caller.

tkinter.filedialog. askopenfile ( mode = ‘r’ , ** options ) ¶ tkinter.filedialog. askopenfiles ( mode = ‘r’ , ** options ) ¶

The above two functions create an Open dialog and return the opened file object(s) in read-only mode.

tkinter.filedialog. asksaveasfile ( mode = ‘w’ , ** options ) ¶

Create a SaveAs dialog and return a file object opened in write-only mode.

tkinter.filedialog. askopenfilename ( ** options ) ¶ tkinter.filedialog. askopenfilenames ( ** options ) ¶

The above two functions create an Open dialog and return the selected filename(s) that correspond to existing file(s).

tkinter.filedialog. asksaveasfilename ( ** options ) ¶

Create a SaveAs dialog and return the selected filename.

tkinter.filedialog. askdirectory ( ** options ) ¶

class tkinter.filedialog. Open ( master = None , ** options ) ¶ class tkinter.filedialog. SaveAs ( master = None , ** options ) ¶

The above two classes provide native dialog windows for saving and loading files.

Convenience classes

The below classes are used for creating file/directory windows from scratch. These do not emulate the native look-and-feel of the platform.

class tkinter.filedialog. Directory ( master = None , ** options ) ¶

Create a dialog prompting the user to select a directory.

The FileDialog class should be subclassed for custom event handling and behaviour.

Create a basic file selection dialog.

cancel_command ( event = None ) ¶

Trigger the termination of the dialog window.

Event handler for double-click event on directory.

Event handler for click event on directory.

Event handler for double-click event on file.

Event handler for single-click event on file.

filter_command ( event = None ) ¶

Filter the files by directory.

Retrieve the file filter currently in use.

Retrieve the currently selected item.

go ( dir_or_file = os.curdir , pattern = ‘*’ , default = » , key = None ) ¶

Render dialog and start event loop.

Exit dialog returning current selection.

Exit dialog returning filename, if any.

Update the current file selection to file.

class tkinter.filedialog. LoadFileDialog ( master , title = None ) ¶

A subclass of FileDialog that creates a dialog window for selecting an existing file.

Test that a file is provided and that the selection indicates an already existing file.

class tkinter.filedialog. SaveFileDialog ( master , title = None ) ¶

A subclass of FileDialog that creates a dialog window for selecting a destination file.

Test whether or not the selection points to a valid file that is not a directory. Confirmation is required if an already existing file is selected.

tkinter.commondialog — Dialog window templates¶

The tkinter.commondialog module provides the Dialog class that is the base class for dialogs defined in other supporting modules.

class tkinter.commondialog. Dialog ( master = None , ** options ) ¶ show ( color = None , ** options ) ¶

Источник

Читайте также:  Page php id play
Оцените статью