python+qt实现记事本
时间: 2023-12-28 19:05:00 浏览: 35
以下是一个简单的Python Qt记事本实现示例:
```
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QAction, QFileDialog
class Notepad(QMainWindow):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.text_edit = QTextEdit()
self.setCentralWidget(self.text_edit)
self.statusBar()
open_act = QAction('Open', self)
open_act.setShortcut('Ctrl+O')
open_act.triggered.connect(self.open_file)
save_act = QAction('Save', self)
save_act.setShortcut('Ctrl+S')
save_act.triggered.connect(self.save_file)
menubar = self.menuBar()
file_menu = menubar.addMenu('File')
file_menu.addAction(open_act)
file_menu.addAction(save_act)
self.setGeometry(300, 300, 600, 400)
self.setWindowTitle('Notepad')
self.show()
def open_file(self):
file_path, _ = QFileDialog.getOpenFileName(self, 'Open File', '', 'Text Files (*.txt);;All Files (*)')
if file_path:
with open(file_path, 'r') as file:
self.text_edit.setText(file.read())
def save_file(self):
file_path, _ = QFileDialog.getSaveFileName(self, 'Save File', '', 'Text Files (*.txt);;All Files (*)')
if file_path:
with open(file_path, 'w') as file:
file.write(self.text_edit.toPlainText())
if __name__ == '__main__':
app = QApplication(sys.argv)
notepad = Notepad()
sys.exit(app.exec_())
```
这个记事本应用程序使用Qt的QMainWindow作为主窗口,并在中央放置了一个QTextEdit小部件。它具有打开和保存文件的功能,可以使用菜单栏上的相应操作或快捷键(Ctrl + O打开文件,Ctrl + S保存文件)。
当打开文件时,应用程序将使用QFileDialog打开文件对话框,读取所选文件的内容,并将其设置为文本编辑器中的文本。当保存文件时,应用程序将使用QFileDialog打开文件对话框,写入文本编辑器中的文本,并将其写入所选文件。
这只是一个简单的示例,可以根据需要进行修改和扩展。
相关推荐
![.zip](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)