Skip to content
파이썬
2023.10.04 23:33

파이썬 랜덤으로 문제풀기 #2

조회 수 79259 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

파이썬 랜덤으로 문제풀기 #2

이번에는 숫자를 입력하는 방식이 아닌 라디오버튼 선택 후 확인버튼을 눌러 정답을 맞추는 방식입니다.

 

 

 

 


import os
import random
from PIL import Image, ImageTk
import tkinter as tk
import pygame
 
# 이미지 폴더 경로
image_folder = r'E:\python\py_code\공\data\과학'
 
# 이미지 파일 목록 생성
image_files = [f for f in os.listdir(image_folder) if f.endswith('.png')]
 
# 하단 GUI 요소를 미리 생성
window = tk.Tk()
window.title("문제 맞추기 게임")
 
# 이미지 표시용 라벨
image_label = tk.Label(window)
image_label.pack(pady=10)
 
# 이미지와 선택 버튼을 포함하는 프레임 생성
frame = tk.Frame(window)
frame.pack()
 
question_label = tk.Label(frame, text="")
question_label.grid(row=0, column=0)
 
# 정답 선택을 위한 라디오 버튼 변수
selected_answer = tk.IntVar()
 
# 정답 선택 라디오 버튼 생성
for i in range(1, 6):
    answer_radio = tk.Radiobutton(frame, text=str(i), variable=selected_answer, value=i)
    answer_radio.grid(row=0, column=i, padx=5)
 
result_label = tk.Label(frame, text="")
result_label.grid(row=1, columnspan=6)
 
# Pygame 초기화 및 MP3 파일 경로 설정
pygame.init()
correct_sound = pygame.mixer.Sound(r'E:\python\py_code\공\ok.mp3')
incorrect_sound = pygame.mixer.Sound(r'E:\python\py_code\공\nono.mp3')
 
def play_correct_sound():
    correct_sound.play()
 
def play_incorrect_sound():
    incorrect_sound.play()
 
def show_random_question():
    # 랜덤하게 이미지 선택
    random_image = random.choice(image_files)
    image_path = os.path.join(image_folder, random_image)
   
    # 이미지 표시
    img = Image.open(image_path)
    img = img.resize((400, 400))
    img = ImageTk.PhotoImage(img)
    image_label.config(image=img)
    image_label.image = img
   
    # 정답 추출
    answer = int(random_image.split('-')[1].split('.')[0])
   
    # 사용자로부터 정답 입력 받기
    def check_answer():
        user_answer = selected_answer.get()
        if user_answer == answer:
            result_label.config(text="정답을 맞췄어요.")
            play_correct_sound()  # 정답 소리 재생
            show_random_question()
        else:
            result_label.config(text="다시 한번 풀어보세요.")
            play_incorrect_sound()  # 오답 소리 재생
   
    # 하단 GUI 업데이트
    selected_answer.set(0)
    result_label.config(text="")
   
    # 하단 GUI 생성
    question_label.config(text="이미지에 나타난 숫자는 무엇일까요?")
   
    # 확인 버튼 생성 (오른쪽에 위치)
    check_button = tk.Button(frame, text="확인", command=check_answer)
    check_button.grid(row=0, column=6)
 
# 초기 문제 표시
show_random_question()
 
# Tkinter 이벤트 루프 시작
window.mainloop()
 
# pygame 종료
pygame.mixer.quit()

 

로그인 후 댓글쓰기가 가능합니다.

?

List of Articles
번호 분류 제목 날짜 조회 수
124 연예정보 김지석 뇌섹남 이진욱 절친활용법 file 2016.05.26 20011
123 연예정보 강인 음주운전 뺑소니 폭행 예비군 다음은? file 2016.05.24 4785
122 연예정보 냉부해 이성재 무식욕자 이유 1 file 2016.05.23 7572
121 연예정보 울산 소바루 생활의 달인의 하얀 메밀국수 file 2016.05.23 4409
120 연예정보 해피투게더 양익준 똥파리 다시 주목 file 2016.05.20 12638
119 연예정보 강남역 묻지마 살인사건 동기와 살인자의 이력 file 2016.05.19 7770
118 연예정보 한강의 채식주의자 내용 file 2016.05.18 13811
117 연예정보 박시연 남편과의 이혼소송 이유 file 2016.05.17 286251
116 연예정보 지연우 보디빌더 선수의 과거 2 file 2016.05.17 131388
115 연예정보 최홍만 권아솔 논란의 중심에 정문홍의 선택 file 2016.05.15 28184
114 연예정보 채널AOA에서 지민 설현 피해자 4 file 2016.05.14 5604
113 연예정보 안재현 구혜선 결혼 꿀 떨어집니다 2 file 2016.05.10 99988
112 연예정보 최성원 급성 백혈병 진단 안타깝네요. 1 file 2016.05.10 9419
111 연예정보 곡성 나홍진 감독의 숨막히는 스릴공포 1 file 2016.05.09 2405
110 연예정보 손흥민 멋진골 사우샘프턴 1:2패 file 2016.05.09 1923
109 연예정보 판타스틱 듀오 엑소 논란이유 2 file 2016.05.08 4239
108 연예정보 김남주 VS 정은지 디스혈전 1 file 2016.05.06 4880
107 연예정보 조세호 차오슈하오와 함께 대세남 왜 안왔어요 3 file 2016.05.05 6831
106 연예정보 신송산업 썩은 밀가루 납품업체 무려 110곳 5 file 2016.05.04 22118
105 연예정보 이상윤 유이 열애 기럭지 커플 흠 좀 잡아보자 file 2016.05.03 17488
Board Pagination Prev 1 ... 3 4 5 6 7 ... 11 Next
/ 11

http://urin79.com

우린친구블로그

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소