我們在利用Python進(jìn)行創(chuàng)建文件時經(jīng)常會用到一些文件路徑,我們可以創(chuàng)建一個選擇文件路徑GUI(PyQt5)界面,然后我們就可以獲取文件的路徑,我們以后就可以直接拿來用?。?/h3>
如下視頻演示
文章來源地址http://www.zghlxwxcb.cn/news/detail-693500.html
程序邏輯
1、點擊【選擇路徑可以選擇文件】
2、【確定(開始執(zhí)行)】這個按鈕沒有綁定函數(shù),大家可以根據(jù)自己的需求綁定函數(shù)
這樣一來我們就可以獲取文件的路徑,并且可以傳遞給其他的函數(shù)內(nèi),并對該文件進(jìn)行處理
完整版代碼:
from PyQt5.QtWidgets import QApplication, QLabel, QPushButton, QLineEdit, QMainWindow, QFileDialog
import sys
class PathSelector(QMainWindow):
def __init__(self):
super().__init__()
self.title = "路徑選擇"
self.width = 500
self.height = 300
self.initUI()
self.filePaths = []
def initUI(self):
# 設(shè)置窗口屬性
self.setWindowTitle(self.title)
self.setGeometry(100, 100, self.width, self.height)
# 標(biāo)簽組件
self.label = QLabel(self)
self.label.setText("選擇文件:")
self.label.move(50, 80)
# 輸入框控件
self.entry_text = QLineEdit(self)
self.entry_text.setFixedSize(250, 30)
self.entry_text.move(150, 80)
self.entry_text.setReadOnly(True)
# 選擇路徑按鈕
self.button = QPushButton(self)
self.button.setText('選擇路徑')
self.button.move(400, 80)
self.button.clicked.connect(self.get_path)
# 確定按鈕
self.submit_button = QPushButton(self)
self.submit_button.setText('確定(開始執(zhí)行)')
self.submit_button.move(155, 150)
self.submit_button.clicked.connect(self.processing_data)
self.show()
# 獲取文件路徑
def get_path(self):
path1, _ = QFileDialog.getOpenFileName(self, "請選擇文件", "", "All Files (*);;Text Files (*.txt)")
self.entry_text.setText(path1)
self.filePaths.append(path1)
# print(self.filePaths)
def processing_data(self):
file_name = self.filePaths[0]
print(file_name)
'''
這里就是你剛剛獲取的文件的處理函數(shù),點擊【確定】按鈕就會開始執(zhí)行
'''
pass
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = PathSelector()
sys.exit(app.exec_())
希望對大家有幫助
致力于辦公自動化的小小程序員一枚#
都看到這了,關(guān)注+點贊+收藏=不迷路?。?/h3>
如果你想知道更多關(guān)于Python辦公自動化的知識各位大佬給個關(guān)注吧!
文章來源:http://www.zghlxwxcb.cn/news/detail-693500.html
到了這里,關(guān)于Python創(chuàng)建一個GUI(PyQt5)選擇文件的界面獲取文件路徑的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!