Use tkinter to make a game? feasible! Very long article, recommended to save!

It is indeed possible to make games using Tkinter. Although Tkinter is primarily used for creating graphical user interfaces (GUIs), it provides enough power and flexibility to make 2D games.

In this article, we will explore how to create a simple 2D game using Tkinter. We will use Python 3 and the Tkinter library to make this game. Along the way, we’ll also learn some useful Python techniques, such as OOP programming and the use of the pygame module.

First, we need to decide what type of game we want to create. Since we are beginners, we will choose a simple game – Snake. Snake is a classic 2D game that allows us to understand how to use Tkinter to create games.

In the Snake game, players control a snake to collect food and extend the length of the snake’s body as much as possible. If the snake hits a border or its own body, the game ends.

Here are the steps we take to make a game:

Step 1: Prepare the Game Window

Creating windows in Tkinter is very simple. We only need to import the Tkinter library, create a main window object and set the window title and size. Here is the code:

import tkinter as tk

#Create the main window
root = tk.Tk()

#Set window title
root.title("Snake Game")

# Set window size
root.geometry("600x600")

# Start window message loop
root.mainloop()

In the above code, we imported the Tkinter library and created a main window object named root. We also set the window title and dimensions, and start the window message loop. Running the above code, we get a simple blank window.

Step 2: Draw the game screen

We need to draw game graphics, including snakes and food. To do this we will use Tkinter’s Canvas object.

The Canvas object allows us to create a drawing area within the window. We can draw geometric shapes and text on the Canvas object and beautify them using properties such as color, fill, and border.

The following code shows how to create a Canvas object and draw a white rectangle inside it as the background of the game:

# Create Canvas object
canvas = tk.Canvas(root, bg="black")

# Draw background rectangle
canvas.create_rectangle(0, 0, 600, 600, fill="white")

# Place the Canvas object in the main window
canvas.pack(fill=tk.BOTH, expand=True)

The above code creates a Canvas object with a size of 600×600 pixels and a black background, and draws a white rectangle inside it. We also use the pack() method to place the Canvas object in the main window.

Step 3: Implement game logic

Next, we need to implement the logic of the game. We need to create a Snake object, which represents a greedy snake, and a Food object, which represents food. We also need to implement some methods to handle user input, move the snake, and detect collisions.

Here is the initial implementation of our Snake class:

class Snake:
    def __init__(self, canvas):
        self.canvas = canvas
        self.segments = [(100, 100), (100, 80), (100, 60)]
        self.direction = "up"
        self.color = "green"
        self.size = 20

        for segment in self.segments:
            x, y = segment
            self.canvas.create_rectangle(x, y, x + self.size, y + self.size, fill=self.color)

    def move(self):
        x, y = self.segments[0]

        if self.direction == "up":
            y -= self.size
        elif self.direction == "down":
            y + = self.size
        elif self.direction == "left":
            x -= self.size
        elif self.direction == "right":
            x + = self.size

        self.segments.pop()
        self.segments.insert(0, (x, y))

        # Update Snake's body
        for i, segment in enumerate(self.segments):
            x, y = segment
            self.canvas.coords(i + 1, x, y, x + self.size, y + self.size)

    def change_direction(self, direction):
        self.direction = direction
</code><img class="look-more-preCode contentImg-no-view" src="//i2.wp.com/csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png" alt ="" title="">

In the above code, we define a Snake class, which has a Canvas object as a property, segments property representing the body of the snake and direction property representing the moving direction of the snake. We also defined some other properties, such as color and size, to beautify the snake.

The Snake class has a move() method for moving the snake. This method moves the snake’s head to the next position and then updates the snake’s body. We use pop() method to remove the last element from the segments list and insert() method to insert new head coordinates at the beginning of the list. We then update the position of the snake’s body elements using the Canvas object’s coords() method.

The Snake class also has a change_direction() method, which is used to change the direction of the snake’s movement. When this method is called, it will change the direction attribute of the Snake class.

Here is the initial implementation of our Food class:

class Food:
    def __init__(self, canvas, size):
        self.canvas = canvas
        self.size = size
        self.color = "red"
        self.x = 0
        self.y = 0
        self.create_food()

    def create_food(self):
        self.canvas.delete("food")

        x = random.randint(0, 29) * self.size
        y = random.randint(0, 29) * self.size

        self.x = x
        self.y = y

        self.canvas.create_rectangle(x, y, x + self.size, y + self.size, fill=self.color, tags="food")
</code><img class="look-more-preCode contentImg-no-view" src="//i2.wp.com/csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png" alt ="" title="">

In the above code, we have defined a Food class, which has a Canvas object as a property and some other properties such as size and color. We also define a create_food() method that is used to generate a new food at a random location and draw it using the create_rectangle() method of the Canvas object.

Step 4: Process user input

We need to handle the user’s keyboard input to change the direction of the snake’s movement. We will use Tkinter’s bind() method to capture keyboard events.

Here is the implementation of our handle_keypress() function:

def handle_keypress(event):
    if event.keysym == "Up":
        snake.change_direction("up")
    elif event.keysym == "Down":
        snake.change_direction("down")
    elif event.keysym == "Left":
        snake.change_direction("left")
    elif event.keysym == "Right":
        snake.change_direction("right")

canvas.bind("<KeyPress>", handle_keypress)

In the code above, we define a handle_keypress() function that accepts a keyboard event as input. According to the key press, this function will call the change_direction() method of the Snake object to change the direction of the snake’s movement.

We also use the bind() method of the Canvas object to bind the “KeyPress” event and the handle_keypress() function. This will allow us to capture events when a keyboard key is pressed.

Step 5: Implement the main game loop

Finally, we need to implement the main loop of the game. This main loop will constantly move the snake, detect collisions, update scores, etc.

Here is the implementation of our game main loop:

def game_loop():
    global score

    snake.move()

    # Detect collision
    x, y = snake.segments[0]

    if x < 0 or x >= 600 or y < 0 or y >= 600:
        game_over()

    for segment in snake.segments[1:]:
        if segment == snake.segments[0]:
            game_over()

    if food.x == x and food.y == y:
        snake.segments.append(snake.segments[-1])
        food.create_food()
        score + = 10
</code><img class="look-more-preCode contentImg-no-view" src="//i2.wp.com/csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png" alt ="" title="">