Skip to content
파이썬
2023.10.04 23:29

파이썬 랜덤으로 시험문제 풀기

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

단축키

Prev이전 문서

Next다음 문서

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

단축키

Prev이전 문서

Next다음 문서

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

파이썬 랜덤으로 시험문제 풀기

 

시험문제를 1-3.png 2-2.png 3-5.png . . . 

로 저장하는데,

 

앞의 번호와 -뒤에 숫자는 문제의 정답번호를 말하는 것입니다.

예를들어 1-3.png 는 1번문제의 정답은 3 입니다.

문제번호를 여러개를 저장한 다음 코딩을 실행하면 랜덤으로 문제가 추출됩니다.

 

1-3.png

 

2-1.png

 

3-3.png

 

4-4.png

 

5-5.png

 

6-2.png

 

7-3.png

 

8-1-모세혈관.2-산소.3-교환.png

 

 


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)
 
entry = tk.Entry(frame)
entry.grid(row=0, column=1, padx=10)
 
result_label = tk.Label(frame, text="")
result_label.grid(row=1, columnspan=2)
 
# 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(event=None):
        user_answer = int(entry.get())
        if user_answer == answer:
            result_label.config(text="정답을 맞췄어요.")
            play_correct_sound()  # 정답 소리 재생
            show_random_question()
        else:
            result_label.config(text="다시 한번 풀어보세요.")
            play_incorrect_sound()  # 오답 소리 재생
   
    # 엔터 키로 정답 확인
    entry.bind("<Return>", check_answer)
   
    # 하단 GUI 업데이트
    entry.delete(0, tk.END)
    result_label.config(text="")
   
    # 하단 GUI 생성
    question_label.config(text="이미지에 나타난 숫자는 무엇일까요?")
   
    # 확인 버튼 생성 (오른쪽에 위치)
    check_button = tk.Button(frame, text="확인", command=check_answer)
    check_button.grid(row=0, column=2)
 
# 초기 문제 표시
show_random_question()
 
# Tkinter 이벤트 루프 시작
window.mainloop()
 
# pygame 종료
pygame.mixer.quit()

 


 

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

?

List of Articles
번호 분류 제목 날짜 조회 수
137 연예정보 20% 요금할인 선택약정할인으로 스마트폰 저렴하게 사용하기 file 2016.10.04 4378
136 연예정보 가애란 아나운서 결혼한 남편 배우자가 누구? 5 file 2016.04.02 101925
135 연예정보 강남역 묻지마 살인사건 동기와 살인자의 이력 file 2016.05.19 7776
134 연예정보 강한나 마리텔 태양 게스트로 시청자들을 삼킬 듯 file 2016.04.10 15494
133 연예정보 걸스데이 소진 영남대 공대여신의 매력녀 4 file 2016.05.30 45420
132 연예정보 계춘할망 윤여정 김고은 디스전 4 file 2016.04.20 39806
131 연예정보 곡성 나홍진 감독의 숨막히는 스릴공포 1 file 2016.05.09 2413
130 연예정보 골프미녀들의 올림픽 금메달 사냥 file 2016.08.18 4616
129 연예정보 공승연 정연 사이에 김민석 견딜 수 있을까? 2 file 2016.06.22 82348
128 연예정보 구의역 사망사고 무엇이 문제인가? file 2016.06.01 3823
127 연예정보 그 멘트 저질 권정열의 논란의 멘트 9 file 2016.06.14 29772
126 연예정보 김가연 딸 임서령 임요환 아빠가 좋아 6 file 2016.04.29 224298
125 연예정보 김고은 공유 도깨비 신부 새드엔딩 file 2016.12.04 15817
124 연예정보 김국진 강수지 열애 전국민이 기다렸다. 2 file 2016.08.04 24940
123 연예정보 김남주 VS 정은지 디스혈전 1 file 2016.05.06 4909
122 연예정보 김동현 닐 매그니 8월 맞대결 2 file 2016.06.28 7660
121 연예정보 김무성과 함께 흥하는 어부바 요령 file 2016.04.15 817
120 연예정보 김상현 입건과 음란행위 사건배경 10 file 2016.07.12 203625
119 연예정보 김세아 회계법인으로 부터 받은 혜택 1 file 2016.05.26 64514
118 연예정보 김원준 결혼 예비신부 검사 이은정 집안 2 file 2016.04.16 344990
Board Pagination Prev 1 2 3 4 5 ... 7 Next
/ 7

http://urin79.com

우린친구블로그

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


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

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

설치 취소