Python日记本程序源代码图形界面
时间: 2024-05-13 13:11:44 浏览: 120
Python日记本程序的图形界面可以使用PyQt5或Tkinter等Python GUI库来实现。下面给您介绍一下使用PyQt5实现的Python日记本程序的源代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QAction, QFileDialog
class Notepad(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.textEdit = QTextEdit(self)
self.setCentralWidget(self.textEdit)
self.statusBar()
openFile = QAction('Open', self)
openFile.setShortcut('Ctrl+O')
openFile.setStatusTip('Open File')
openFile.triggered.connect(self.showDialog)
saveFile = QAction('Save', self)
saveFile.setShortcut('Ctrl+S')
saveFile.setStatusTip('Save File')
saveFile.triggered.connect(self.saveDialog)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(openFile)
fileMenu.addAction(saveFile)
self.setGeometry(300, 300, 350, 300)
self.setWindowTitle('Notepad')
self.show()
def showDialog(self):
fname = QFileDialog.getOpenFileName(self, 'Open File', '/home')
if fname:
with open(fname, 'r') as f:
data = f.read()
self.textEdit.setText(data)
def saveDialog(self):
fname = QFileDialog.getSaveFileName(self, 'Save File', '/home')
if fname:
with open(fname, 'w') as f:
data = self.textEdit.toPlainText()
f.write(data)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Notepad()
sys.exit(app.exec_())
```
该程序使用了QMainWindow作为主窗口,使用QTextEdit作为文本编辑区域。程序提供了菜单栏,可以通过菜单栏打开和保存文件。打开文件和保存文件的具体实现都调用了Qt提供的文件对话框。您可以运行该程序来查看界面效果。
阅读全文