1、前言
在學習Pyqt5過程中,遇到了想通過按鈕等控件打開檔案夾,類似于下面(圖1)的 '打開檔案夾一樣' 的效果
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnL0AzN3IjMzETMzIjNwAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
(圖1)
本來以為PyQt5 會有類似于QFileDialog 的檔案對話框進行檔案夾打開浏覽,但并沒有發現。
在進一步查找資料發現可以通過Python 中内置os 子產品庫可以達到打開檔案夾要求。
2、pyqt5實作打開檔案夾
首先在D盤建立一個用于測試的檔案夾(我的如下面 圖2)
(圖2)
下面直接放代碼,建立py檔案直接複制即可使用。
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'openfoldertest.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(320, 240)
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(80, 80, 111, 31))
self.pushButton.setObjectName("pushButton")
self.retranslateUi(Form)
#點選按鈕信号傳送到打開檔案夾函數
self.pushButton.clicked.connect(self.openfolder)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "打開檔案夾"))
def openfolder(self,Form):
'''打開系統檔案資料總管的對應檔案夾'''
import os
folder = r'D:\aatest'
#方法1:通過start explorer
os.system("start explorer %s" %folder)
# 方法2:通過startfile
os.startfile(folder)
if __name__ == "__main__":
import sys
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)# 适配2k等高分辨率螢幕,低分辨率螢幕可除去
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
運作點選‘打開檔案夾按鈕’結果如下面圖3
(圖3)
3、分析與說明
如上面代碼,我用了兩種方法打開檔案夾,是以會彈出兩個檔案軟體視窗。在實際使用選其一即可。比較推薦方法2。
方法1:
#方法1:通過start explorer
os.system("start explorer %s" %folder)
方法2:
# 方法2:通過startfile
os.startfile(folder)