[Python] 구글 번역기 앱 만들기

Legday_Dev·2024년 3월 2일
0

Python

목록 보기
1/3
post-thumbnail

Python 으로 구글 번역기 앱을 만들기 위해서 우선 googletrans 모듈을 설치해야 한다.
명령어 : pip install googletrans==3.1.0a0

UI 만들기


UI 는 Qt Designer 를 이용하여 만들었다.

  • m1 macOS 에서 설치한 거라 Windows 와는 다른 화면일 수 있다.
  • Qt Designer 로 UI 파일을 저장하면 xml 형태로 저장이 된다.
    <?xml version="1.0" encoding="UTF-8"?>
    <ui version="4.0">
      <class>Form</class>
      <widget class="QWidget" name="Form">
        <property name="geometry">
          <rect>
            <x>0</x>
            <y>0</y>
            <width>320</width>
            <height>390</height>
          </rect>
        </property>
        <property name="maximumSize">
          <size>
            <width>320</width>
            <height>390</height>
          </size>
        </property>
        <property name="windowTitle">
          <string>QR Code Generator</string>
        </property>
        <widget class="QLabel" name="lblQrCode">
          <property name="geometry">
            <rect>
              <x>10</x>
              <y>10</y>
              <width>300</width>
              <height>300</height>
            </rect>
          </property>
          <property name="styleSheet">
            <string notr="true">background-color: white;
            </string>
          </property>
          <property name="text">
            <string/>
          </property>
        </widget>
        <widget class="QLineEdit" name="txtQrData">
          <property name="geometry">
            <rect>
              <x>10</x>
              <y>320</y>
              <width>301</width>
              <height>21</height>
            </rect>
          </property>
        </widget>
        <widget class="QPushButton" name="btnGenerate">
          <property name="geometry">
            <rect>
              <x>200</x>
              <y>350</y>
              <width>111</width>
              <height>41</height>
            </rect>
          </property>
          <property name="font">
            <font>
              <family>D2Coding</family>
            </font>
          </property>
          <property name="text">
            <string>QR 코드 생성</string>
          </property>
        </widget>
      </widget>
      <resources/>
      <connections/>
    </ui>

코드 설명


  • QWidget 을 상속받는 qrApp 클래스를 만든다.
    • qrApp 클래스에서 UI 와 기능을 구현하는 함수들이 들어간다.
    • myTrans 라는 멤버필드를 선언하고 googletrans 모듈에 있는 Translator 클래스를 생성자로 초기화한다.
    • 생성자 호출 시 Qt Designer로 만든 UI 화면을 실행하는 initUI 함수를 실행한다.
  • Qt Designer 로만든 UI 파일을 화면에 띄우는 initUi 함수를 설정한다.
    • uic 모듈에서 loadUi() 함수를 호출하여 Qt Designer 로 만든 UI 파일을 불러온다.
    • setWindowTitle() 함수는 윈도우 창의 제목을 설정하는 함수다.
    • btnTrans 는 버튼위젯의 이름이고 해당 버튼을 clicked 했을 때 호출하는 함수를 connect() 함수로 연결시켜준다.
    • returnPressed엔터키를 눌렀을 때 버튼클릭했을 때와 같은 기능을 구현하게 해주는 함수이다.
  • btnTransClicked() 는 버튼을 클릭했을 때 실행하는 함수이다.
    • 번역할 텍스트를 입력하는 위젯의 이름은 txtBaseText 이다. 입력된 텍스트를 text() 로 문자열로 변환 후, strip() 으로 좌,우 공백을 지워주고 text 변수에 저장한다.
    • 입력한 텍스트가 비어있지 않다면 myTrans 멤버변수의 tranlate() 함수를 호출하여 text 를 넘겨주고 번역전 문자열의 언어는 자동으로 설정하고 번역되는 문자는 영어로 번역한다.
    • 그리고 txtResult 위젯의 번역전 문자열과 번역 후 문자열을 출력해준다.
  • closeEvent() 함수는 윈도우 창을 종료할 때 종료할 것인지 경고창을 출력하는 함수이다.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

from googletrans import Translator


class qrApp(QWidget):
    def __init__(self) -> None:
        super().__init__()
        self.initUI()
        self.myTrans = Translator()

    def initUI(self):
        uic.loadUi("./day07/transApp.ui", self)
        self.setWindowTitle("Google Translate App")
        self.btnTrans.clicked.connect(self.btnTransClicked)
        self.txtBaseText.returnPressed.connect(self.btnTransClicked)
        self.show()

    def btnTransClicked(self):
        # QMessageBox.about(self, "번역", "번역시작...")
        text = self.txtBaseText.text().strip()
        if len(text) != 0:
            result = self.myTrans.translate(text, src="auto", dest="en")
            self.txbResult.append(f'{text} -> {result.text}')

        pass

    def closeEvent(self, QCloseEvent) -> None:
        re = QMessageBox.question(
            self, "종료", "종료 하시겠습니까?", QMessageBox.Cancel | QMessageBox.Yes
        )
        if re == QMessageBox.Yes:
            QCloseEvent.accept()
        else:
            QCloseEvent.ignore()


app = QApplication(sys.argv)
app.setWindowIcon(QIcon("./images/QrCodeIcon.png"))
instance = qrApp()
app.exec_()

실행화면


profile
백엔드개발자

0개의 댓글