Python点击按钮,浏览本地文件夹,选择文件夹并输入文件名称后将路径输出到line edit,代码怎么写
时间: 2024-02-19 13:03:05 浏览: 140
可以使用PyQt5模块来实现Python GUI界面的编写和文件夹选择功能的实现,下面是一个示例代码:
```python
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtWidgets import QFileDialog
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 400, 300)
self.setWindowTitle('File Explorer')
self.folder_path_label = QtWidgets.QLabel(self)
self.folder_path_label.setText('Folder Path:')
self.folder_path_label.move(20, 20)
self.folder_path_edit = QtWidgets.QLineEdit(self)
self.folder_path_edit.setGeometry(120, 20, 250, 20)
self.browse_button = QtWidgets.QPushButton(self)
self.browse_button.setText('Browse')
self.browse_button.setGeometry(300, 50, 70, 25)
self.browse_button.clicked.connect(self.browse_folder)
self.filename_label = QtWidgets.QLabel(self)
self.filename_label.setText('File Name:')
self.filename_label.move(20, 80)
self.filename_edit = QtWidgets.QLineEdit(self)
self.filename_edit.setGeometry(120, 80, 250, 20)
self.save_button = QtWidgets.QPushButton(self)
self.save_button.setText('Save')
self.save_button.setGeometry(300, 110, 70, 25)
self.save_button.clicked.connect(self.save_file)
self.show()
def browse_folder(self):
folder_path = QFileDialog.getExistingDirectory(self, 'Select Folder')
self.folder_path_edit.setText(folder_path)
def save_file(self):
file_path = self.folder_path_edit.text() + '/' + self.filename_edit.text()
with open('output.txt', 'w') as f:
f.write(file_path)
self.filename_edit.clear()
self.folder_path_edit.clear()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
main_window = MainWindow()
sys.exit(app.exec_())
```
这个程序会在界面中显示一个文件夹路径输入框、浏览按钮、文件名输入框和保存按钮。当用户点击浏览按钮后,会弹出一个文件夹选择框,用户可以选择一个文件夹,并将选择的文件夹路径显示在输入框中。用户还需要在界面中输入一个文件名,然后点击保存按钮,程序会将文件夹路径和文件名拼接起来,将最终的文件路径输出到output.txt文件中。
阅读全文