pyqt5读取指定txt文件并显示
时间: 2023-09-10 13:08:38 浏览: 253
可以使用QFileDialog选择指定的txt文件,然后使用QTextBrowser将文件内容显示出来。代码如下:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QTextBrowser, QPushButton, QFileDialog
class MainWindow(QWidget):
def __init__(self):
super().__init__()
# 创建一个按钮和一个文本框
self.button = QPushButton('选择文件', self)
self.button.move(20, 20)
self.button.clicked.connect(self.show_dialog)
self.textbox = QTextBrowser(self)
self.textbox.move(20, 60)
self.textbox.resize(280, 200)
self.setGeometry(100, 100, 320, 280)
self.show()
def show_dialog(self):
# 打开文件选择对话框
filename, _ = QFileDialog.getOpenFileName(self, '选择文件', '.', 'Text files (*.txt)')
if filename:
# 读取文件内容并显示在文本框中
with open(filename, 'r', encoding='utf-8') as f:
self.textbox.setText(f.read())
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
```
运行程序后,点击按钮选择txt文件,文件内容会在文本框中显示出来。