728x90
728x90

간단한 CRUD(Create, Read, Update, Delete) 프로그램

들어가며

  • PyQt5로 간단한 CRUD(Create, Read, Update, Delete) 기능을 수행할 수 있는 프로그램을 만들어보자.

 

코드

  • @QTextEdit@ 위젯을 이용하여 CRUD 기능을 수행할 수 있는 메모장과 비슷한 프로그램이다.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QAction, QFileDialog

class TextEditor(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.textEdit = QTextEdit(self)
        self.setCentralWidget(self.textEdit)

        self.initMenuBar()

        self.setGeometry(100, 100, 800, 600)
        self.setWindowTitle('Text Editor')
        self.show()

    def initMenuBar(self):
        menubar = self.menuBar()

        fileMenu = menubar.addMenu('File')

        openAction = QAction('Open', self)
        openAction.setShortcut('Ctrl+O')
        openAction.triggered.connect(self.openFile)

        saveAction = QAction('Save', self)
        saveAction.setShortcut('Ctrl+S')
        saveAction.triggered.connect(self.saveFile)

        fileMenu.addAction(openAction)
        fileMenu.addAction(saveAction)

    def openFile(self):
        options = QFileDialog.Options()
        options |= QFileDialog.ReadOnly
        fileName, _ = QFileDialog.getOpenFileName(self, 'Open File', '', 'Text Files (*.txt)', options=options)
        if fileName:
            with open(fileName, 'r') as file:
                self.textEdit.setText(file.read())

    def saveFile(self):
        options = QFileDialog.Options()
        options |= QFileDialog.ReadOnly
        fileName, _ = QFileDialog.getSaveFileName(self, 'Save File', '', 'Text Files (*.txt)', options=options)
        if fileName:
            with open(fileName, 'w') as file:
                file.write(self.textEdit.toPlainText())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = TextEditor()
    sys.exit(app.exec_())

 

728x90
728x90