Tkinter를 사용한 2D 게임 시작하기 (Part 2): 게임 화면 만들기

발행: (2025년 12월 24일 오전 11:30 GMT+9)
6 min read
원문: Dev.to

I’m happy to translate the article for you, but I’ll need the full text you’d like translated. Could you please paste the content (excluding the source line you already provided) here? Once I have the text, I’ll translate it into Korean while preserving the original formatting, markdown, and code blocks.

게임 화면 만들기

이 문서에서는 Tkinter의 Canvas를 사용해 게임 화면을 만드는 방법을 알아봅니다.

1. 작업 폴더 준비

  1. 작업 폴더를 만들고 main.py라는 파일을 추가합니다.
    파일 생성 방법에 대한 자세한 내용은
    Saving a Program to a File을 참고하세요.

  2. 작업 폴더 안에 images 디렉터리를 생성합니다. 모든 이미지 자산은 이곳에 저장됩니다.

  3. 아래 이미지를 다운로드하여 images 폴더 안에 bg_jigoku.png라는 이름으로 저장합니다.

    Background image

    (익숙한 지옥 같은 모습이죠?)

폴더 구조는 다음과 같이 됩니다:

working_folder/
 ├─ main.py               # 메인 프로그램 파일
 └─ images/
     └─ bg_jigoku.png     # 배경 이미지

앞으로는 모든 코드를 main.py 파일에 작성합니다.

2. Tkinter 객체 만들기

tkinter 라이브러리를 임포트하고, 제목이 있는 루트 윈도우를 생성합니다.
윈도우 크기 조절을 비활성화하면 게임 영역이 고정된 크기로 유지됩니다.

import tkinter

root = tkinter.Tk()                 # Tkinter 객체 생성
root.title("Hello, Tkinter!!")      # 윈도우 제목
root.resizable(False, False)       # 윈도우 크기 조절 비활성화

3. Canvas 만들기

캔버스 크기를 변수 W(너비)와 H(높이)로 정의한 뒤, 해당 크기로 Canvas 위젯을 생성합니다.

import tkinter

# Canvas 너비와 높이
W, H = 480, 320

root = tkinter.Tk()
root.title("Hello, Tkinter!!")
root.resizable(False, False)

canvas = tkinter.Canvas(root, width=W, height=H)
canvas.pack()

이제 프로그램을 실행하면 480 × 320 픽셀 크기의 창이 나타납니다.

다음 단계에서는 배경 이미지를 로드하고, 전체 화면 전환을 처리하며, 나머지 게임 화면을 구축하는 코드를 추가해 보세요.

Canvas

import tkinter

W, H = 480, 320

root = tkinter.Tk()
root.title("Hello, Tkinter!!")
root.resizable(False, False)

cvs = tkinter.Canvas(width=W, height=H, bg="black")
cvs.pack()

root.mainloop()

From now on we will draw background images and character images on this canvas.

Canvas example

4. Prepare an Initialization Function

게임 시작 시 한 번 실행되는 초기화 함수와 화면을 지속적으로 갱신하는 업데이트 함수를 준비합니다. 초기화 로직과 업데이트 로직을 분리하면 전체 코드가 훨씬 깔끔해집니다.

init() 함수 안의 pass 문은 *“아무것도 하지 않음”*을 의미합니다(나중에 채워질 예정).

import tkinter

W, H = 480, 320

def init():
    """Initialization function."""
    pass

root = tkinter.Tk()
root.title("Hello, Tkinter!!")
root.resizable(False, False)

cvs = tkinter.Canvas(width=W, height=H, bg="black")
cvs.pack()

init()
update()          # will be defined later
root.mainloop()

5. Prepare an Update Function

F_RATE를 사용해 프레임 레이트를 정의합니다.
프레임 레이트는 초당 화면이 업데이트되는 횟수를 의미합니다.
이론적으로는 ~60 fps가 이상적이지만, 이번 연습에서는 30 fps를 사용합니다.

F_INTERVAL은 한 프레임당 시간 간격(밀리초)입니다.
update() 안에서 root.after(F_INTERVAL, update)를 호출해 다음 업데이트를 예약합니다.

import tkinter

W, H = 480, 320

# Frame rate
F_RATE = 30
F_INTERVAL = int(1000 / F_RATE)

def init():
    """Initialization function."""
    pass

def update():
    """Update function."""
    root.after(F_INTERVAL, update)

root = tkinter.Tk()
root.title("Hello, Tkinter!!")
root.resizable(False, False)

cvs = tkinter.Canvas(width=W, height=H, bg="black")
cvs.pack()

init()
update()
root.mainloop()

6. Place the Background Image

init() 안에서 배경 이미지를 로드하고 배치합니다.
이미지 파일은 images 폴더에 있는 bg_jigoku.png입니다.

PhotoImage 객체가 가비지 컬렉션되지 않도록 global 키워드가 필요합니다.

# Background image (global variables)
bg_photo, bg_image = None, None

def init():
    """Initialization function."""
    global bg_photo, bg_image

    bg_photo = tkinter.PhotoImage(file="images/bg_jigoku.png")
    bg_image = cvs.create_image(W / 2, H / 2, image=bg_photo)

지금까지 완성된 코드

import tkinter

W, H = 480, 320

F_RATE = 30
F_INTERVAL = int(1000 / F_RATE)

bg_photo, bg_image = None, None

def init():
    global bg_photo, bg_image
    bg_photo = tkinter.PhotoImage(file="images/bg_jigoku.png")
    bg_image = cvs.create_image(W / 2, H / 2, image=bg_photo)

def update():
    root.after(F_INTERVAL, update)

root = tkinter.Tk()
root.title("Hello, Tkinter!!")
root.resizable(False, False)

cvs = tkinter.Canvas(width=W, height=H, bg="black")
cvs.pack()

init()
update()
root.mainloop()

Resulting window

다음 내용…

읽어 주셔서 감사합니다!
다음 글은 “마우스 이벤트 사용하기.” 입니다. 기대해 주세요!

Back to Blog

관련 글

더 보기 »