PyQt(4) - 예제

Gyeomii·2022년 6월 24일
0

DDITPython

목록 보기
9/18
post-thumbnail

📌 홀짝게임

코드

**import sys
from PyQt5.QtWidgets import *
from PyQt5 import uic
from dask.array.random import randint

#UI파일 연결
form_class = uic.loadUiType("myQt05.ui")[0]

#화면을 띄우는데 사용되는 Class 선언
class WindowClass(QMainWindow, form_class) :
    def __init__(self) :
        super().__init__()
        self.setupUi(self)
        #버튼에 기능을 연결하는 코드
        self.pb.clicked.connect(self.oddEven)
				#LineEdit에 값을 넣고 Enter를 치면 기능이 실행되도록 연결하는 코드
				self.qle1.returnPressed.connect(self.oddEven)
        
    #pb가 눌리면 작동할 함수
    def oddEven(self) :
        User = self.qle1.text()
        com = self.comRand()
        if(User == com):
            result = "User 승리"
        else:
            result = "Com 승리"
        self.qle2.setText(com)
        self.qle3.setText(result)
        
    def comRand(self):
        com = ""
        rnd = randint(0,2)
        if(rnd == 0):
            com = "짝"
        else:
            com = "홀"
        return com
               
        
if __name__ == "__main__" :
    app = QApplication(sys.argv) 
    myWindow = WindowClass() 
    myWindow.show()
    app.exec_()**

설명

**#버튼에 기능을 연결하는 코드
self.pb.clicked.connect(self.oddEven)
#LineEdit에 값을 넣고 Enter를 치면 기능이 실행되도록 연결하는 코드
self.qle1.returnPressed.connect(self.oddEven)**
**def comRand(self):
		com = ""
		# 0 ~ 1까지 random 정수 생성
    rnd = randint(0,1+1)
    if(rnd == 0):
        com = "짝"
    else:
        com = "홀"
    return com**
  • 랜덤 함수를 이용해 컴퓨터의 홀 짝을 생성하는 함수
  • 홀 짝 판별 함수에 호출되어 사용된다.
  • randInt(start,end+1) : start부터 end 사이의 랜덤한 정수를 반환하는 함수
    • randInt(0,2) : 0 ~ 1까지 랜덤 정수를 반환함
    • 직관성을 높이기 위해 randInt(0,1+1)로 표현
**#pb가 눌리면 작동할 함수
def oddEven(self) :
		# qle1의 텍스트 가져오기
    User = self.qle1.text()
		# 위에서 선언한 comRand()함수 호출하여 com변수에 담기
    com = self.comRand()
		# 홀짝 판별
    if(User == com):
        result = "User 승리"
    else:
        result = "Com 승리"
		qle2, qle3에 출력
    self.qle2.setText(com)
    self.qle3.setText(result)**

실행 결과

📌 로또 번호 생성

코드

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

# UI파일 연결
form_class = uic.loadUiType("myQt06.ui")[0]

# 화면을 띄우는데 사용되는 Class 선언
class WindowClass(QMainWindow, form_class):

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # 버튼에 기능을 연결하는 코드
        self.pb.clicked.connect(self.createRotto)
        
    # pb가 눌리면 작동할 함수
    def createRotto(self):
        num = []
        # 리스트에 1 ~ 45 담기
        for i in range(1, 46):
            num.append(i)
        # num리스트에 담긴 데이터 중 무작위로 7개 뽑아서 rotto에 담기
        rotto = []
        for i in range(0, 7):
            rotto.append(secrets.choice(num))
						rottoSet = list(set(rotto))
        
        # 정렬하기
        rottoSet.sort()
        # 출력
        self.lbl1.setText(str(rottoSet[0]))
        self.lbl2.setText(str(rottoSet[1]))
        self.lbl3.setText(str(rottoSet[2]))
        self.lbl4.setText(str(rottoSet[3]))
        self.lbl5.setText(str(rottoSet[4]))
        self.lbl6.setText(str(rottoSet[5]))
				#여러번 실행을 위해 리스트 비우기
				num.clear()
        rotto.clear()
        rottoSet.clear()

        
if __name__ == "__main__":
    app = QApplication(sys.argv) 
    myWindow = WindowClass() 
    myWindow.show()
    app.exec_()

설명

    # pb가 눌리면 작동할 함수
    def createRotto(self):
        num = []
        # 리스트에 1 ~ 45 담기
        for i in range(1, 46):
            num.append(i)
        # num리스트에 담긴 데이터 중 무작위로 7개 뽑아서 rotto에 담기
        rotto = []
        for i in range(0, 7):
            rotto.append(secrets.choice(num))
						rottoSet = list(set(rotto))
        
        # 정렬하기
        rottoSet.sort()
        # 출력
        self.lbl1.setText(str(rottoSet[0]))
        self.lbl2.setText(str(rottoSet[1]))
        self.lbl3.setText(str(rottoSet[2]))
        self.lbl4.setText(str(rottoSet[3]))
        self.lbl5.setText(str(rottoSet[4]))
        self.lbl6.setText(str(rottoSet[5]))
				#여러번 실행을 위해 리스트 비우기
				num.clear()
        rotto.clear()
        rottoSet.clear()
  • 리스트
    • num = [] :리스트를 생성
    • num.append(0) : 리스트 0번째에 0 이 담김
    • num.sort() : 오름차순으로 정렬
    • num[0] : 0번째 데이터
    • num.clear() : 리스트 비우기

실행 결과

📌 가위바위보

코드

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

# UI파일 연결
form_class = uic.loadUiType("myQt07.ui")[0]

# 화면을 띄우는데 사용되는 Class 선언
class WindowClass(QMainWindow, form_class):

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # 버튼에 기능을 연결하는 코드
        self.pb.clicked.connect(self.rsp)
        self.qle1.returnPressed.connect(self.rsp)
        
    #pb가 눌리면 작동할 함수
    def rsp(self) :
        user = self.qle1.text()
        comList = ["가위", "바위", "보"]
        com = secrets.choice(comList)
        if(user == com):
            result = "비김"
        elif(user == "가위" and com == "보" 
             or user == "바위" and com == "가위" 
             or user == "보" and com == "바위"):
            result = "User 승리"
        else:
            result = "COM 승리"
        self.qle2.setText(com)
        self.qle3.setText(result)

if __name__ == "__main__":
    app = QApplication(sys.argv) 
    myWindow = WindowClass() 
    myWindow.show()
    app.exec_()

설명

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

# UI파일 연결
form_class = uic.loadUiType("myQt07.ui")[0]

# 화면을 띄우는데 사용되는 Class 선언
class WindowClass(QMainWindow, form_class):

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # 버튼에 기능을 연결하는 코드
        self.pb.clicked.connect(self.rsp)
        self.qle1.returnPressed.connect(self.rsp)
        
    #pb가 눌리면 작동할 함수
    def rsp(self) :
        user = self.qle1.text()
        comList = ["가위", "바위", "보"]
				#secrets.choice(데이터집합) : 데이터집합 안에서 무작위 값 한개 리턴
        com = secrets.choice(comList)
        if(user == com):
            result = "비김"
        elif(user == "가위" and com == "보" 
             or user == "바위" and com == "가위" 
             or user == "보" and com == "바위"):
            result = "User 승리"
        else:
            result = "COM 승리"
        self.qle2.setText(com)
        self.qle3.setText(result)

if __name__ == "__main__":
    app = QApplication(sys.argv) 
    myWindow = WindowClass() 
    myWindow.show()
    app.exec_()

설명

		#pb가 눌리면 작동할 함수
    def rsp(self) :
        user = self.qle1.text()
        comList = ["가위", "바위", "보"]
				#secrets.choice(데이터집합) : 데이터집합 안에서 무작위 값 한개 리턴
        com = secrets.choice(comList)
        if(user == com):
            result = "비김"
        elif(user == "가위" and com == "보" 
             or user == "바위" and com == "가위" 
             or user == "보" and com == "바위"):
            result = "User 승리"
        else:
            result = "COM 승리"
        self.qle2.setText(com)
        self.qle3.setText(result)
  • secrets.choice(데이터 집합) : 데이터 집합 안에서 무작위 데이터 1개를 리턴한다.
  • comList에 “가위”, “바위”, “보”를 담고 secrets.choice(comList)를 하면 셋 중 한개 값 반환

실행 결과

profile
김성겸

0개의 댓글