[AI] Python GUI

Bora Kwon·2022년 5월 30일
0

Qt5 사용해서 만들 수 있음.

import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, qApp, QFileDialog, QPushButton, QLabel

# QtCore 모듈의 QCoreApplication 클래스 가져 오기
from PyQt5.QtCore import QCoreApplication
from pkg_resources import FileMetadata


class MyApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        # 아이콘 추가
        self.setWindowIcon(QIcon("./MicrosoftTeams-image.png"))

        # 프레임 만들기
        self.setWindowTitle("My First Application")
        self.move(300, 300)
        self.resize(400, 200)

        # 상태 바 초기값
        self.statusBar().showMessage("준비중....")

        # 푸시 버튼
        self.label = QLabel('00000000', self)
        self.move(40, 40)
        self.pb = QPushButton("Start", self)
        self.pb.clicked.connect(self.count_number)
        self.pb.move(150, 40)

        # 메뉴 바
        exitAction = QAction('&Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip("Exit Application")
        exitAction.triggered.connect(qApp.quit)

        menubar = self.menuBar()

        loadfile = QAction('Load file ...', self)
        savefile = QAction('Save file ...', self)
        loadfile.triggered.connect(self.add_open)
        savefile.triggered.connect(self.add_save)

        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)
        fileMenu.addAction(loadfile)
        fileMenu.addAction(savefile)
        self.show()

    def add_open(self):
        FileOpen = QFileDialog.getOpenFileName(self, 'Open file ', './')
        print(FileOpen)

    def add_save(self):
        FileSave = QFileDialog.getSaveFileName(self, 'Save file ', './')
        print(FileSave)

    def count_number(self):
        # 상태 바 생성 코드
        self.statusBar().showMessage("작업중....")   

        self.statusBar().repaint()
        for i in range(1, 10000):
            print(i)
            self.label.setText(str(i))
            self.label.repaint()
        self.statusBar().showMessage("준비중...")



if __name__ == "__main__":
    # 모든 PyQt5 어플리케이션은 어플리케이션 객체 생성
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

Box Layout

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QVBoxLayout

"""
구성
창의 가운데 아래에 두 개의 버튼을 배치
두개의 버튼은 창의 크기를 변화시켜도 같은 자리에 위치합니다. 
"""


class MyApp(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        # 두개의 버튼 만들기
        okButton = QPushButton('ok')
        cancelButton = QPushButton('Cancel')

        """
            수평 박스를 하나 만들고, 두개의 버튼과 양쪽에 빈 공간 추가 합니다. 
            addStretch() 메서드는 신축성있는 빈공간을 제공합니다
            두 버튼 양쪽의 stretch factor 1로 같기 떄문에 이 두 빈공간의 크기는 창의 크기가 변화해도 항상 동일 
        """
        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(okButton)
        hbox.addWidget(cancelButton)
        hbox.addStretch(1)

        vbox = QVBoxLayout()
        vbox.addStretch(3)
        vbox.addLayout(hbox)
        vbox.addStretch(1)

        # 최종적으로 수직 박스를 창의 메인 레이어아웃으로 설정
        self.setLayout(vbox)
        self.setWindowTitle("Box Layout")
        self.setGeometry(300, 300, 300, 200)
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

Slider

from PyQt5.QtWidgets import QWidget, QSlider, QHBoxLayout, QLabel, QApplication
from PyQt5.QtCore import Qt

import sys


class MyApp(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        hbox = QHBoxLayout()

        sld = QSlider(Qt.Vertical, self)
        sld.setFocusPolicy(Qt.NoFocus)

        sld.setRange(0, 100)
        sld.setPageStep(5)
        sld.valueChanged.connect(self.changeValue)

        self.label = QLabel("0", self)
        self.label.setStyleSheet(
            "Qlabel { background: #007AA5; border-radius : 3px;}")
        self.label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        self.label.setMinimumWidth(80)

        hbox.addStretch()
        hbox.addWidget(sld)
        hbox.addSpacing(15)
        hbox.addWidget(self.label)
        hbox.addStretch()

        self.setLayout(hbox)

        self.setGeometry(300, 300, 350, 250)
        self.setWindowTitle("QSlider")
        self.show()

    def changeValue(self, value):

        self.label.setText(str(value))


def main():

    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())


if __name__ == "__main__":

    main()
profile
Software Developer

0개의 댓글