기록하는 코더

[Python] PyQt 기본 예제 본문

Python

[Python] PyQt 기본 예제

damda_di 2022. 12. 30. 16:35

Android 예제와 같이 진행할 예정이다.

 

  1. 버튼 누르면 글자 바꾸기
  2. 버튼 누르면 숫자가 1씩 증가
  3. 구구단 출력하기
  4. 홀짝게임
  5. 로또 번호 출력
  6. 가위바위보
  7. 별찍기
  8. 다이얼 만들기
  9. 입력 숫자 더하기
  10. 입력 숫자 범위 내에 있는 배수의 합 구하기
  11. 야구 게임

 

0. 공통 코드

import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic

form_class = uic.loadUiType("main01.ui")[0]

#화면을 띄우는데 사용되는 Class 선언
class WindowClass(QMainWindow, form_class) :
    def __init__(self) :
        super().__init__()
        self.setupUi(self)
        
        self.pb.clicked.connect(self.btn_event)
        
    def btn_event(self):
    
       **** 클릭시 실행되는 이벤트 내용이 기술되는 공간****       
        

if __name__ == "__main__" :
    #QApplication : 프로그램을 실행시켜주는 클래스
    app = QApplication(sys.argv) 

    #WindowClass의 인스턴스 생성
    myWindow = WindowClass() 

    #프로그램 화면을 보여주는 코드
    myWindow.show()

    #프로그램을 이벤트루프로 진입시키는(프로그램을 작동시키는) 코드
    app.exec_()

 

다른 함수를 실행할때마다 designer 툴에서 수정한 ui 이름이 맞는지 확인하고 다르다면 바꿔줘야 한다!

form_class = uic.loadUiType("main02.ui")[0]

 

1. 버튼 누르면 글자 바꾸기

더보기

main01.py

...공통코드 공간...
		if self.lbl.text() == "Good Morning":
            self.lbl.setText("Good Evening")
        else:            
            self.lbl.setText("Good Morning")
...공통코드 공간...
라벨의 입력된 텍스트 값을 가져와 텍스트값에 따라 버튼을 클릭하면 다른 문구가 뜨도록 했다.

 

출력화면

버튼을 누르면 문구가 바뀐다.

 

2. 버튼 누르면 숫자가 1씩 증가

더보기

main02.py

...공통코드 공간...
	def __init__(self) :
        super().__init__()
        self.setupUi(self)
        
        self.pb.clicked.connect(self.btn_event)
        
    def btn_event(self):
        num = int(self.le.text())
        num += 1
        strNum = str(num)
        self.le.setText(strNum)    
...공통코드 공간...

 

출력화면

버튼을 누르면 

 

3. 구구단 출력하기

더보기

main03.py

... 공통코드 공간...
    def btn_event(self):
        numStr = (self.le.text())
        numInt = int(numStr)
        
        code = ""
        for i in range(1,9+1):
            code += "{} * {} = {}\n".format(i,numStr,numInt*i)           
        self.te.setText(code)
      
 ... 공통코드 공간...

출력화면

 

 

4. 홀짝게임

더보기

main04.py

...공통코드 공간...
    def btn_event(self):
        user = self.le1.text()
        if not (user=="홀" or user=="짝"):
            self.le3.setText("홀,짝 중에서 입력해주세요.")
            return False
        
        arr = ['홀','짝']
        com = random.choice(arr)

        if user == com:
            self.le2.setText(com)
            self.le3.setText("이겼습니다.")
        else:
            self.le2.setText(com)
            self.le3.setText("졌습니다.")
...공통코드 공간...

출력화면

 

 

5. 로또 번호 출력

더보기

main05.py

...공통코드 공간...
def btn_event(self):
        arr=[
            1,2,3,4,5,      6,7,8,9,10,
            11,12,13,14,15,16,18,19,20,
            21,22,23,24,25,26,27,28,29,30,
            31,32,33,34,35,36,37,38,39,40,
            41,42,43,44,45]
        
        for i in range(1000):
            rnd = int(random.random()*len(arr))
            a = arr[rnd]
            b = arr[0]
            arr[0] = a
            arr[rnd] = b
            
        # list로 배열 확인
        # print(list(arr))
        
        # 로또 번호 세팅
        self.lbl1.setText(str(arr[0]))
        self.lbl2.setText(str(arr[1]))
        self.lbl3.setText(str(arr[2]))
        self.lbl4.setText(str(arr[3]))
        self.lbl5.setText(str(arr[4]))
        self.lbl6.setText(str(arr[5]))
...공통코드 공간...

 

랜덤섞기 다른 방법

         random.shuffle(arr)

 

 출력화면

 

 

6. 가위바위보 게임

더보기

main06.py

...공통코드 공간...
# 가위바위보 게임
class WindowClass(QMainWindow, form_class) :
    def __init__(self) :
        super().__init__()
        self.setupUi(self)
        
        self.pb.clicked.connect(self.btn_event)
        self.leMine.returnPressed.connect(self.btn_event)
        
    def btn_event(self):
        user = self.leMine.text()
        com = ""
        result = ""
        
        rnd = random.random()
        if rnd > 0.66:
            com ="가위"
        elif rnd > 0.33:
            com="바위"
        else:
            com="보"
            
        if user == "가위" and com == "가위" : result = "비김"
        if user == "가위" and com == "바위" : result = "이김"
        if user == "가위" and com == "보" : result = "짐"
        
        if user == "바위" and com == "가위" : result = "짐"
        if user == "바위" and com == "바위" : result = "비김"
        if user == "바위" and com == "보" : result = "이김"
        
        if user == "보" and com == "가위" : result = "이김"
        if user == "보" and com == "바위" : result = "짐"
        if user == "보" and com == "보" : result = "비김"

        self.leCom.setText(com)
        self.leResult.setText(result)
        
...공통코드 공간...

 

다른 방법

...공통코드공간...
	def btn_event(self):
        user = self.leMine.text()
        
		arr = ['가위','바위','보']
        com = random.choice(arr)
        result =""
        if not (user =='가위' or user =='바위' or user == '보'):
            result += "가위,바위,보를 입력!" 
        
        if user == '가위' and com == '바위': result += '졌습니다.'
        if user == '가위' and com == '가위': result += '비겼습니다.'    
        if user == '가위' and com == '보': result += '이겼습니다.'
        
        if user == '바위' and com == '바위': result += '비겼습니다.'
        if user == '바위' and com == '가위': result += '이겼습니다.'    
        if user == '바위' and com == '보': result += '졌습니다.'
        
        if user == '보' and com == '바위': result += '이겼습니다.'
        if user == '보' and com == '가위': result += '졌습니다.'    
        if user == '보' and com == '보': result += '비겼습니다.'

        self.leCom.setText(com)
        self.leResult.setText(result)
...공통코드공간...
# arr choice 함수를 이용해서 랜덤결과 얻기

	arr = ['가위','바위','보']
    com = random.choice(arr)
    result =""
    if not (user =='가위' or user =='바위' or user == '보'):
        result += "가위,바위,보를 입력!"

출력화면

 

 

게임하기 버튼을 클릭하지 않아도 엔터키를 누르면 결과가 나온다.

 

 

7. 별찍기

더보기

main07.py

...공통코드 공간...
    def __init__(self) :
        super().__init__()
        self.setupUi(self)
        
        self.pb.clicked.connect(self.myclick)
        
    def drawStar(self,cnt):
        ret = ""
        for i in range(cnt):
            ret += "*"
        ret += "\n"
        return ret 
    
    def myclick(self):
        f = self.le_first.text()
        l = self.le_last.text()
        ff = int(f)
        ll = int(l)
        
        txt =""
        for i in range(ff, ll+1):
            txt += self.drawStar(i)
            
        self.pte.setPlainText(txt)
...공통코드 공간...

출력화면

 

 

8. 다이얼 만들기

더보기

main08.py

...공통코드 공간...
  def __init__(self) :
        super().__init__()
        self.setupUi(self)
        
        self.pb0.clicked.connect(self.addNum)
        self.pb1.clicked.connect(self.addNum)
        self.pb2.clicked.connect(self.addNum)
        self.pb3.clicked.connect(self.addNum)
        self.pb4.clicked.connect(self.addNum)
        self.pb5.clicked.connect(self.addNum)
        self.pb6.clicked.connect(self.addNum)
        self.pb7.clicked.connect(self.addNum)
        self.pb8.clicked.connect(self.addNum)
        self.pb9.clicked.connect(self.addNum)
        self.pbCall.clicked.connect(self.myclick)
        
        
    def addNum(self):
        btn = self.sender()
        print(btn)
        btnText = btn.text()
        strNew = btnText
        strOld = self.le.text() + strNew        
        
        self.le.setText(strOld)
        
    def myclick(self):
        QMessageBox.about(self,"Calling",self.le.text()+"에게 전화를 겁니다...")


...공통코드 공간...

 

출력화면

 

번호키를 누르면 QLineEdit에 출력되도록 했다.

 

Call을 누르면 QMessageBox가 뜬다.

 

9. 입력 숫자 더하기

더보기

main09.py

...공통코드 공간...
    def __init__(self) :
        super().__init__()
        self.setupUi(self)
        
        self.pb.clicked.connect(self.myclick)
        
        
    def myclick(self):
        a = self.leA.text()
        b = self.leB.text()
        
        aa = int(a)
        bb = int(b)
        
        result = aa * bb
        
        res = str(result)
        self.leC.setText(res)

..공통코드 공간...

 

출력화면

 

 

A. 입력 숫자 범위 내에 있는 배수의 합 구하기

더보기

mainA.py

...공통코드 공간...
    def __init__(self) :
        super().__init__()
        self.setupUi(self)
        
        self.pb.clicked.connect(self.myclick)
        
        
    def myclick(self):
        a = self.leA.text()
        b = self.leB.text()
        
        aa = int(a)
        bb = int(b)
        
        result = aa * bb
        
        res = str(result)
        self.leC.setText(res)


...공통코드 공간...

출력화면

 

B. 야구 게임

더보기

 mainB.py

...공통코드 공간...
	def __init__(self):
        super().__init__()
        self.com = "123"
        self.setupUi(self)
        self.pb.clicked.connect(self.myclick)
        self.randomCom()
        
    def randomCom(self):
        arr = ["1","2","3","4","5",    "6","7","8","9"]
        
        for i in range(100):
            rnd = int(random.random()*len(arr))
            a = arr[rnd];
            b = arr[0];
            arr[0]=a;
            arr[rnd]=b;
        
        self.com = arr[0]+arr[1]+arr[2]
        print("self.com",self.com)
        
                
    def myclick(self):
        mine = self.le.text()
        s = self.getStrike(self.com,mine)
        b = self.getBall(self.com,mine)
        
        str_old = self.te.toPlainText()
        str_new = mine +"  "+str(s)+"S"+str(b)+"B"+"\n"

        self.te.setText(str_old+str_new)
        self.le.setText("")
        
        if s == 3:
            QMessageBox.about(self,'스트라이크','맞췄습니다.{}'.format(self.com))
        
    def getBall(self,com,mine):
        ret = 0
        c1 = com[0:1]
        c2 = com[1:2]
        c3 = com[2:3]
        
        m1 = mine[0:1]
        m2 = mine[1:2]
        m3 = mine[2:3]
        
        if c1 == m2 or c1 == m3 : ret+=1
        if c2 == m1 or c2 == m3 : ret+=1
        if c3 == m1 or c3 == m2 : ret+=1
        
        return ret
        
    def getStrike(self,com,mine):
        ret = 0
        c1 = com[0:1]
        c2 = com[1:2]
        c3 = com[2:3]
        
        m1 = mine[0:1]
        m2 = mine[1:2]
        m3 = mine[2:3]
        
        if c1 == m1 : ret+=1
        if c2 == m2 : ret+=1
        if c3 == m3 : ret+=1
        
        return ret
...공통코드 공간...

 

 

출력화면

 

'Python' 카테고리의 다른 글

[Python] FastAPI 사용해보기  (0) 2023.01.05
[Python] pymssql 활용 - 01  (0) 2023.01.04
[Python] PyQt 이용하기  (0) 2022.12.30
[Python] OOP(Object Oriented Programming)  (0) 2022.12.26
[Python] function  (1) 2022.12.24