DEV Community

Kajiru
Kajiru

Posted on

Getting Started with 2D Games Using Tkinter (Part 2): Creating the Game Screen

Creating the Game Screen

In this article, we will create the game screen using Tkinter’s Canvas.

1. Prepare a Working Folder

First, create a working folder and create a file called main.py.

For details on how to create files, please refer to

Saving a Program to a File.

Next, create an images folder.

All image assets will be stored in this folder.

Please use the following image as the background.

(It looks like a familiar kind of hell, doesn’t it?)

Your folder structure should look like this:

working_folder/
 ├ main.py        # main program file
 └ images/
    └ bg_jigoku.png  # background image
Enter fullscreen mode Exit fullscreen mode

From now on, we will write all code in the main.py file.

2. Create a Tkinter Object

First, import the tkinter library and create an object using tkinter.Tk().

In the following example, we set the window title and disable window resizing for the created root object.

import tkinter

root = tkinter.Tk()                 # Create a Tkinter object
root.title("Hello, Tkinter!!")      # Window title
root.resizable(False, False)        # Disable window resizing
Enter fullscreen mode Exit fullscreen mode

3. Create a Canvas

Prepare variables W and H to represent the width and height of the game screen.

(This will be useful later!)

Next, create a canvas using tkinter.Canvas().

If you run the program at this point, a game window with a size of 480 × 320 pixels will appear.

import tkinter

# Canvas width and height
W, H = 480, 320

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

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

root.mainloop()
Enter fullscreen mode Exit fullscreen mode

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

4. Prepare an Initialization Function

We will prepare an initialization function that runs at the start of the game, and an update function that continuously refreshes the screen.

Separating initialization logic from update logic makes the overall code much cleaner.

The pass statement in the init() function means “do nothing”.

(It is empty for now, but we will add code here later.)

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()
root.mainloop()
Enter fullscreen mode Exit fullscreen mode

5. Prepare an Update Function

Next, define the frame rate using F_RATE.

The frame rate means how many times the screen is updated per second.

A frame rate of around 60 is ideal, but since this is practice, we will use 30.

F_INTERVAL represents the time interval for one frame (in milliseconds).

Inside the update() function, we write root.after(F_INTERVAL, update).

This means “call the update() function again after F_INTERVAL milliseconds.”

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()
Enter fullscreen mode Exit fullscreen mode

6. Place the Background Image

Now, load and place the background image inside the initialization function.

The image we use is bg_jigoku.png, located in the images folder.

The global keyword allows us to use variables defined outside the function.

Without it, the image may be garbage-collected and will not appear on the screen.

# 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)
Enter fullscreen mode Exit fullscreen mode

Complete Code

Here is the complete code with all features implemented so far.

(Welcome to hell!!)

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()
Enter fullscreen mode Exit fullscreen mode

Coming Up Next...

Thank you very much for reading.

The title of the next article will be “Using Mouse Events.”

Stay tuned!!

Top comments (0)