프로그램&회로

Copilot으로 무식한 상태에서 프로그램 짜기...

엠칩 2024. 9. 2. 17:08
반응형

"계산기 프로그램 을 짜고 싶어"부터 시작할 수 있지만...
초기단계에서 너무 오래걸리니.. 좀 스킵하여... 적당한 명령을 내려보기로 하자...

물론 초보자에겐 이마저도 쉽지 않다. pip install PyQt5 명령을 어떻게 해야 하는지 다시 물어봐야 하고
파이썬 설치도 안해본 사람이라면 파이썬 프로그램을 어떻게 설치하고 실행하는지도 물어봐야 한다...
물론 자신의 상태를 알리고 물어보면 친절하게 잘 가르쳐 준다. 
아래는 결과 값... 에러 없이 잘 실행된다.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLineEdit, QGridLayout, QPushButton

class Calculator(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Calculator')
        self.setGeometry(100, 100, 300, 400)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.display = QLineEdit()
        self.layout.addWidget(self.display)

        self.buttons = QGridLayout()
        self.layout.addLayout(self.buttons)

        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '0', '.', '=', '+'
        ]

        row, col = 0, 0
        for button in buttons:
            btn = QPushButton(button)
            btn.clicked.connect(self.on_click)
            self.buttons.addWidget(btn, row, col)
            col += 1
            if col > 3:
                col = 0
                row += 1

    def on_click(self):
        sender = self.sender()
        text = sender.text()

        if text == '=':
            try:
                result = eval(self.display.text())
                self.display.setText(str(result))
            except Exception as e:
                self.display.setText('Error')
        else:
            self.display.setText(self.display.text() + text)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    calculator = Calculator()
    calculator.show()
    sys.exit(app.exec_())
AI가 생성한 코드입니다. 신중하게 검토하고 사용하세요. FAQ의 자세한 정보.

이 코드는 간단한 계산기 프로그램을 구현합니다. 버튼을 클릭하면 해당 숫자나 연산자가 디스플레이에 표시되고, = 버튼을 클릭하면 결과가 계산되어 표시됩니다.

이 예제를 바탕으로 더 복잡한 기능을 추가하거나 UI를 커스터마이징할 수 있습니다. 추가적인 도움이 필요하면 언제든지 말씀해주세요! 😊

 
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLineEdit, QGridLayout, QPushButton

class Calculator(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Calculator')
        self.setGeometry(100, 100, 300, 400)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.display = QLineEdit()
        self.layout.addWidget(self.display)

        self.buttons = QGridLayout()
        self.layout.addLayout(self.buttons)

        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '0', '.', '=', '+'
        ]

        row, col = 0, 0
        for button in buttons:
            btn = QPushButton(button)
            btn.setFixedHeight(50)  # 버튼 높이 설정
            btn.clicked.connect(self.on_click)
            self.buttons.addWidget(btn, row, col)
            col += 1
            if col > 3:
                col = 0
                row += 1

    def on_click(self):
        sender = self.sender()
        text = sender.text()

        if text == '=':
            try:
                result = eval(self.display.text())
                self.display.setText(str(result))
            except Exception as e:
                self.display.setText('Error')
        else:
            self.display.setText(self.display.text() + text)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    calculator = Calculator()
    calculator.show()
    sys.exit(app.exec_())
AI가 생성한 코드입니다. 신중하게 검토하고 사용하세요. FAQ의 자세한 정보.

이제 각 버튼의 높이가 50 픽셀로 설정됩니다. 필요에 따라 높이를 조정할 수 있습니다. 더 궁금한 점이 있으면 언제든지 말씀해주세요! 😊

 
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLineEdit, QGridLayout, QPushButton
from PyQt5.QtCore import Qt

class Calculator(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Calculator')
        self.setGeometry(100, 100, 300, 400)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.display = QLineEdit()
        self.layout.addWidget(self.display)

        self.buttons = QGridLayout()
        self.layout.addLayout(self.buttons)

        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '0', '.', '=', '+'
        ]

        row, col = 0, 0
        for button in buttons:
            btn = QPushButton(button)
            btn.setFixedHeight(50)  # 버튼 높이 설정
            btn.clicked.connect(self.on_click)
            self.buttons.addWidget(btn, row, col)
            col += 1
            if col > 3:
                col = 0
                row += 1

    def on_click(self):
        sender = self.sender()
        text = sender.text()

        if text == '=':
            try:
                result = eval(self.display.text())
                self.display.setText(str(result))
            except Exception as e:
                self.display.setText('Error')
        else:
            self.display.setText(self.display.text() + text)

    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Enter or key == Qt.Key_Return:
            self.on_click_equal()
        elif key == Qt.Key_Backspace:
            self.display.backspace()
        else:
            self.display.setText(self.display.text() + event.text())

    def on_click_equal(self):
        try:
            result = eval(self.display.text())
            self.display.setText(str(result))
        except Exception as e:
            self.display.setText('Error')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    calculator = Calculator()
    calculator.show()
    sys.exit(app.exec_())
AI가 생성한 코드입니다. 신중하게 검토하고 사용하세요. FAQ의 자세한 정보.

이제 키보드 입력도 계산기 프로그램에 연결되었습니다. Enter 키를 누르면 결과가 계산되고, Backspace 키를 누르면 한 글자씩 지워집니다. 다른 키를 누르면 해당 키가 디스플레이에 추가됩니다.

 
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTextEdit, QGridLayout, QPushButton
from PyQt5.QtCore import Qt

class Calculator(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Calculator')
        self.setGeometry(100, 100, 300, 400)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.display = QTextEdit()
        self.display.setReadOnly(True)
        self.display.setFixedHeight(100)  # 높이 설정
        self.layout.addWidget(self.display)

        self.buttons = QGridLayout()
        self.layout.addLayout(self.buttons)

        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '0', '.', '=', '+'
        ]

        row, col = 0, 0
        for button in buttons:
            btn = QPushButton(button)
            btn.setFixedHeight(50)  # 버튼 높이 설정
            btn.clicked.connect(self.on_click)
            self.buttons.addWidget(btn, row, col)
            col += 1
            if col > 3:
                col = 0
                row += 1

    def on_click(self):
        sender = self.sender()
        text = sender.text()

        if text == '=':
            self.on_click_equal()
        else:
            self.display.insertPlainText(text)

    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Enter or key == Qt.Key_Return:
            self.on_click_equal()
        elif key == Qt.Key_Backspace:
            self.display.textCursor().deletePreviousChar()
        else:
            self.display.insertPlainText(event.text())

    def on_click_equal(self):
        try:
            result = eval(self.display.toPlainText())
            self.display.append(f"= {result}")
        except Exception as e:
            self.display.append("Error")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    calculator = Calculator()
    calculator.show()
    sys.exit(app.exec_())
AI가 생성한 코드입니다. 신중하게 검토하고 사용하세요. FAQ의 자세한 정보.

이제 입력과 결과가 QTextEdit 위젯에 표시되며, 다섯 줄을 넘으면 스크롤이 가능합니다. 추가적인 도움이 필요하면 언제든지 말씀해주세요! 😊

 
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTextEdit, QGridLayout, QPushButton
from PyQt5.QtCore import Qt

class Calculator(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Calculator')
        self.setGeometry(100, 100, 300, 400)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.display = QTextEdit()
        self.display.setReadOnly(True)
        self.display.setFixedHeight(100)  # 높이 설정
        self.layout.addWidget(self.display)

        self.buttons = QGridLayout()
        self.layout.addLayout(self.buttons)

        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '0', '.', '=', '+',
            'CE'
        ]

        row, col = 0, 0
        for button in buttons:
            btn = QPushButton(button)
            btn.setFixedHeight(50)  # 버튼 높이 설정
            btn.clicked.connect(self.on_click)
            self.buttons.addWidget(btn, row, col)
            col += 1
            if col > 3:
                col = 0
                row += 1

    def on_click(self):
        sender = self.sender()
        text = sender.text()

        if text == '=':
            self.on_click_equal()
        elif text == 'CE':
            self.display.clear()
        else:
            self.display.insertPlainText(text)

    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Enter or key == Qt.Key_Return:
            self.on_click_equal()
        elif key == Qt.Key_Backspace:
            self.display.textCursor().deletePreviousChar()
        else:
            self.display.insertPlainText(event.text())

    def on_click_equal(self):
        try:
            result = eval(self.display.toPlainText())
            self.display.append(f"= {result}")
        except Exception as e:
            self.display.append("Error")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    calculator = Calculator()
    calculator.show()
    sys.exit(app.exec_())

 

AI가 생성한 코드입니다. 신중하게 검토하고 사용하세요. FAQ의 자세한 정보.

이제 CE 버튼을 클릭하면 디스플레이가 초기화됩니다. 추가적인 도움이 필요하면 언제든지 말씀해주세요! 😊

 

일단 여기까지 이렇게 짰다. 일반적인 연산은 문제 없는데 문제를 일으키면 문제가 된다.

 

Python
 
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTextEdit, QGridLayout, QPushButton
from PyQt5.QtCore import Qt

class Calculator(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Calculator')
        self.setGeometry(100, 100, 300, 400)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.display = QTextEdit()
        self.display.setReadOnly(True)
        self.display.setFixedHeight(100)  # 높이 설정
        self.layout.addWidget(self.display)

        self.buttons = QGridLayout()
        self.layout.addLayout(self.buttons)

        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '0', '.', '=', '+',
            'CE'
        ]

        row, col = 0, 0
        for button in buttons:
            btn = QPushButton(button)
            btn.setFixedHeight(50)  # 버튼 높이 설정
            btn.clicked.connect(self.on_click)
            self.buttons.addWidget(btn, row, col)
            col += 1
            if col > 3:
                col = 0
                row += 1

    def on_click(self):
        sender = self.sender()
        text = sender.text()

        if text == '=':
            self.on_click_equal()
        elif text == 'CE':
            self.display.clear()
        else:
            self.display.insertPlainText(text)

    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Enter or key == Qt.Key_Return:
            self.on_click_equal()
        elif key == Qt.Key_Backspace:
            self.display.textCursor().deletePreviousChar()
        else:
            self.display.insertPlainText(event.text())

    def on_click_equal(self):
        try:
            result = eval(self.display.toPlainText())
            self.display.append(f"\n{result}")
        except Exception as e:
            self.display.append("\nError")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    calculator = Calculator()
    calculator.show()
    sys.exit(app.exec_())

이제 결과값이 = 부호 없이 표시되므로, 다음 연산을 이어 나갈 때 문제가 발생하지 않을 것입니다. 추가적인 도움이 필요하면 언제든지 말씀해주세요! 😊

AI가 생성한 코드입니다. 신중하게 검토하고 사용하세요. FAQ의 자세한 정보.

Python
 
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTextEdit, QGridLayout, QPushButton
from PyQt5.QtCore import Qt

class Calculator(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Calculator')
        self.setGeometry(100, 100, 300, 400)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.display = QTextEdit()
        self.display.setReadOnly(True)
        self.display.setFixedHeight(100)  # 높이 설정
        self.layout.addWidget(self.display)

        self.buttons = QGridLayout()
        self.layout.addLayout(self.buttons)

        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '0', '.', '=', '+',
            'CE'
        ]

        row, col = 0, 0
        for button in buttons:
            btn = QPushButton(button)
            btn.setFixedHeight(50)  # 버튼 높이 설정
            btn.clicked.connect(self.on_click)
            self.buttons.addWidget(btn, row, col)
            col += 1
            if col > 3:
                col = 0
                row += 1

    def on_click(self):
        sender = self.sender()
        text = sender.text()

        if text == '=':
            self.on_click_equal()
        elif text == 'CE':
            self.display.clear()
        else:
            self.display.insertPlainText(text)

    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Enter or key == Qt.Key_Return:
            self.on_click_equal()
        elif key == Qt.Key_Backspace or key == Qt.Key_Delete:
            self.display.clear()
        else:
            self.display.insertPlainText(event.text())

    def on_click_equal(self):
        try:
            result = eval(self.display.toPlainText())
            self.display.append(f"\n{result}")
        except Exception as e:
            self.display.append("\nError")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    calculator = Calculator()
    calculator.show()
    sys.exit(app.exec_())
AI가 생성한 코드입니다. 신중하게 검토하고 사용하세요. FAQ의 자세한 정보.

이제 CE 버튼을 클릭하거나 키보드의 Delete 키를 누르면 디스플레이가 초기화됩니다. 추가적인 도움이 필요하면 언제든지 말씀해주세요! 😊

 

Python
 
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTextEdit, QGridLayout, QPushButton
from PyQt5.QtCore import Qt

class Calculator(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('Calculator')
        self.setGeometry(100, 100, 300, 400)

        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        self.display = QTextEdit()
        self.display.setReadOnly(True)
        self.display.setFixedHeight(100)  # 높이 설정
        self.layout.addWidget(self.display)

        self.buttons = QGridLayout()
        self.layout.addLayout(self.buttons)

        buttons = [
            '7', '8', '9', '/',
            '4', '5', '6', '*',
            '1', '2', '3', '-',
            '0', '.', '=', '+',
            'CE', '<'
        ]

        row, col = 0, 0
        for button in buttons:
            btn = QPushButton(button)
            btn.setFixedHeight(50)  # 버튼 높이 설정
            btn.clicked.connect(self.on_click)
            self.buttons.addWidget(btn, row, col)
            col += 1
            if col > 3:
                col = 0
                row += 1

    def on_click(self):
        sender = self.sender()
        text = sender.text()

        if text == '=':
            self.on_click_equal()
        elif text == 'CE':
            self.display.clear()
        elif text == '<':
            self.display.textCursor().deletePreviousChar()
        else:
            if self.display.toPlainText().endswith("Error"):
                self.display.clear()
            self.display.insertPlainText(text)

    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Enter or key == Qt.Key_Return:
            self.on_click_equal()
        elif key == Qt.Key_Backspace:
            self.display.textCursor().deletePreviousChar()
        elif key == Qt.Key_Delete:
            self.display.clear()
        else:
            if self.display.toPlainText().endswith("Error"):
                self.display.clear()
            self.display.insertPlainText(event.text())

    def on_click_equal(self):
        try:
            result = eval(self.display.toPlainText())
            self.display.append(f"\n{result}")
        except Exception as e:
            self.display.append("\nError")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    calculator = Calculator()
    calculator.show()
    sys.exit(app.exec_())
AI가 생성한 코드입니다. 신중하게 검토하고 사용하세요. FAQ의 자세한 정보.

이제 < 버튼을 클릭하거나 백스페이스 키를 누르면 한 글자씩 지워지며, 연산 결과가 Error인 경우 다음 연산을 새로 입력할 수 있습니다. 추가적인 도움이 필요하면 언제든지 말씀해주세요! 😊

이로서 사칙연산 기본 프로그램이 완성되었다.

여기에 과학산술연산기능이나 이것저것 필요한 기능들 추가하고 싶으면 copilot을 시키면 된다.!!

 

 

 

반응형

'프로그램&회로' 카테고리의 다른 글

전구소켓 규격 E26 E17  (0) 2024.09.19
Copilot  (0) 2024.08.27
EMS EMI EMC  (0) 2024.07.10
VL53L1 address  (0) 2024.05.16
VL53L1 i2clog data  (0) 2024.05.16