Skip to content
파이썬
2023.10.04 23:33

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

조회 수 79418 추천 수 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
번호 분류 제목 날짜 조회 수
100 WindowsTip 윈도우10 ALT + TAB 창 전환이 안될 때 대처방법 file 2022.03.09 9185
99 WindowsTip ISO 파일을 USB에 굽는 방법 [4GB 넘는 ISO 파일 USB에 굽는 방법] 2019.04.13 8113
98 WindowsTip vcruntime140.dll / vcomp140.dll / vcamp140.dll 오류해결법 2016.09.06 6842
97 WindowsTip Visual Studio 2015용 Visual C++ 재배포 설치 오류 해결방법 3 file 2016.09.06 15440
96 WindowsTip 윈도우 CPU 사용률 확인, 실시간 저장하기 2016.08.24 5685
95 WindowsTip 도스에서 텍스트 파일 치환 2016.07.19 4626
94 WindowsTip 예약된 작업(작업 스케줄러 시작) 2016.03.26 4098
93 WindowsTip Diskless Boot Software for Windows(윈도우용 노하드 시스템) 2 file 2016.01.11 8583
92 WindowsTip DOS Batch - FTP Scripts 배치파일 2015.11.12 5702
91 WindowsTip 윈도우 ip helper ipv6 도데체 무엇인가? 2015.05.11 4916
90 WindowsTip 캐논 MG 2990 스캔 드라이버 file 2015.05.03 4715
89 WindowsTip 캐논 프린터 MG2990 드라이버 file 2015.05.03 5300
88 WindowsTip Fasoo DRM 삭제하기(fph) file 2015.04.13 10664
87 WindowsTip UEFI 부팅+윈도우 8.1 2015.04.13 6218
86 WindowsTip 윈도우 8.1 부팅속도 개선방법 2015.04.13 4813
85 WindowsTip 윈도우 8.1 시작화면 아닌 바탕화면(데스크톱 모드)를 기본으로 설정하는 방법 file 2015.04.02 7557
84 WindowsTip 윈도우8.1 암호 입력없이 자동로그인 하기 2015.04.01 4359
83 WindowsTip 윈도우 8.1 업데이트 하지 않기 file 2015.03.21 3777
82 WindowsTip 인터넷 익스플로러 기본검색 공급자 설정해제 file 2015.03.21 4291
81 WindowsTip 윈도우 8.1 종료버튼 만들기 file 2015.03.21 3851
Board Pagination Prev 1 2 3 4 5 Next
/ 5

http://urin79.com

우린친구블로그

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


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

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

설치 취소