728x90
반응형
>> 무한루프 발생 문제 해결❣️
from PIL import Image, ImageDraw, ImageFont
# 파일 경로 설정
template_path = "C:/Users/MJ/Desktop/월간리포트만들기/template.png" # 템플릿 이미지
grade_graph_path = "C:/Users/MJ/Desktop/월간리포트만들기/bg.png" # 성적 그래프
progress_graph_path = "C:/Users/MJ/Desktop/월간리포트만들기/bp.png" # 진도 그래프
font_path = "C:/Users/MJ/Desktop/월간리포트만들기/NanumGothic.ttf" # 한글 폰트
# 템플릿 및 그래프 이미지 로드
template = Image.open(template_path)
grade_graph = Image.open(grade_graph_path)
progress_graph = Image.open(progress_graph_path)
# 텍스트 피드백 준비
feedback_text = """무한 루프 문제는 코드가 특정 종료 조건을 충족하지 못해 계속해서 반복 실행되는 현상입니다. 이번 코드에서는 텍스트가 지정된 박스 크기에 맞도록 글자 크기와 줄 간격을 조정하는 과정에서, 특정 조건이 만족되지 않아 무한 반복이 발생했습니다. 이를 방지하려면 최소 글자 크기 제한을 설정하고, 루프 내에서 적절한 탈출 조건을 추가해야 합니다. 예를 들어, 일정 횟수 이상 반복되면 강제로 중단하는 방식을 사용할 수 있습니다. Debugging 시에는 print() 문을 활용해 루프 내 변수 변화를 확인하고, 실행이 멈추지 않을 경우 Ctrl + C를 눌러 강제 종료하면 됩니다."""
# 텍스트 박스 설정
text_box_x = 226
text_box_y = 5334
text_box_width = 4156 # 텍스트 박스 폭
text_box_height = 1021 # 텍스트 박스 높이
# 폰트 크기 및 줄 간격 설정
font_size = 100
min_font_size = 50
max_font_size = 120
line_spacing = 20
max_iterations = 100 # 무한 루프 방지
iteration = 0
# 텍스트 크기 조정 루프
while iteration < max_iterations:
iteration += 1 # 반복 횟수 증가
font = ImageFont.truetype(font_path, font_size)
wrapped_text = []
current_line = ""
for word in feedback_text.split():
test_line = f"{current_line} {word}".strip()
bbox = font.getbbox(test_line)
text_width = bbox[2] - bbox[0]
if text_width <= text_box_width:
current_line = test_line
else:
wrapped_text.append(current_line)
current_line = word
wrapped_text.append(current_line)
# 전체 텍스트 높이 계산
total_height = sum(font.getbbox(line)[3] - font.getbbox(line)[1] + line_spacing for line in wrapped_text) - line_spacing
# 텍스트 크기 조정
if total_height > text_box_height:
font_size -= 2
line_spacing = max(10, line_spacing - 1)
elif total_height < text_box_height * 0.9:
font_size += 2
line_spacing += 1
else:
break # 박스에 적절히 맞으면 종료
# 최소 글자 크기 제한
if font_size < min_font_size:
print("⚠️ 글자 크기가 너무 작아졌습니다. 텍스트 크기 조정을 중단합니다.")
font_size = min_font_size
break
# 디버깅 메시지 출력
print(f"Iteration {iteration}: Font Size = {font_size}, Line Spacing = {line_spacing}")
# 루프 종료 확인
if iteration == max_iterations:
print("🚨 경고: 최대 반복 횟수를 초과하여 루프를 종료합니다.")
print("✅ 최종 텍스트 배치 완료")
# 텍스트 삽입
draw = ImageDraw.Draw(template)
y_position = text_box_y
for line in wrapped_text:
draw.text((text_box_x, y_position), line, font=font, fill="black")
y_position += font.getbbox(line)[3] - font.getbbox(line)[1] + line_spacing
# 그래프 크기 및 위치 설정
grade_graph = grade_graph.resize((4234, 2142))
progress_graph = progress_graph.resize((4270, 1356))
template.paste(grade_graph, (196, 992))
template.paste(progress_graph, (178, 3511))
# PDF로 저장
pdf_path = "C:/Users/MJ/Desktop/월간리포트만들기/MonthlyReport.pdf"
template.save(pdf_path, "PDF", resolution=200.0)
print("🎉 성적표 PDF가 성공적으로 생성되었습니다!")
>> 결과물
>>결론
포기 안하면 됨
경험이 중요
코드 안 돌아가도 짜증 내지 않기
728x90
반응형