Skip to content
파이썬
2023.10.04 23:29

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

조회 수 94312 추천 수 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
번호 분류 제목 날짜 조회 수
157 컴퓨터잡담 G-PON 시스템의 이해 11 2010.12.17 9749
156 컴퓨터잡담 Full HD Digital TV 1080i 와 1080p 차이점 file 2013.05.10 13253
155 컴퓨터잡담 FTP 자동 업로드 사용방법 2 2012.03.26 5574
154 컴퓨터잡담 float 문제, Image 밑으로 본문을 새로 줄바꿈해서 출력하려면. file 2010.12.08 5044
153 Server FileZilla FTP SERVER 패시브모드 셋팅방법 file 2016.12.22 8803
152 WindowsTip Fasoo DRM 삭제하기(fph) file 2015.04.13 10838
151 프로세스 EzClick.exe / ezbho.dll 프로세스 삭제방법 2 2011.02.13 18614
150 [Docs]스프레드시트 Extending Google Sheets 2015.02.10 4647
149 WindowsTip exFAT 이동식 USB 하드 쓰기 금지 문제 해결방법 2015.01.22 3116
148 컴퓨터잡담 Excel에서 틀 고정 방법 2010.09.04 18628
147 Excel Excel) 엑셀에서 셀 입력시 자동 추가글 넣기 file 2013.06.09 24073
146 Excel Excel) 엑셀 콤보박스 대화상자 목록지정하기 2011.12.21 29396
145 컴퓨터잡담 EXCEL) 매크로 공부하기 2011.09.25 12281
144 컴퓨터잡담 eXCEL VBA)엑셀파일 열지않고 내용 불러오기 3 2011.10.23 30524
143 컴퓨터잡담 Excel VBA)OpenDatabase 방법 [Excel 2003의 VBA 언어 참조] 3 2011.10.23 13889
142 Excel Excel Vba) 현재 셀에서 한줄내림 (activecell.offset(1,0).Select) 3 2012.01.05 31063
141 컴퓨터잡담 ExCEL VBA) 함수만들기 1 2011.09.25 14014
140 컴퓨터잡담 ExCEL VBA) 파일을 열지않고 값 읽어오기 23 2011.09.25 20222
139 컴퓨터잡담 Excel VBA) 파일 이름에 따라 이미지 출력 4 2011.11.25 16210
138 컴퓨터잡담 ExCEL VBA) 중복된 데이터 추출하기 4 2011.09.25 20202
Board Pagination Prev 1 ... 37 38 39 40 41 ... 46 Next
/ 46

http://urin79.com

우린친구블로그

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


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

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

설치 취소