Step-by-Step Tutorial: Creating a ‘Guess the Random Number’ Game in Python with Tkinter

Posted by


In this tutorial, we will create a simple ‘Guess the Random Number’ game using Python and the Tkinter library for building the graphical user interface. The game will generate a random number between 1 and 100, and the player will have to guess the correct number within a limited number of attempts.

Step 1: Install Tkinter (if you haven’t already)
If you are using Python 3, Tkinter should already be included in your installation. However, if you are using Python 2, you will need to install Tkinter separately. You can do this by running the following command in your terminal:

sudo apt-get install python-tk

Step 2: Import necessary libraries
First, we need to import the random module for generating random numbers and the Tkinter module for creating the GUI. Add the following code at the beginning of your Python script:

import random
import tkinter as tk
from tkinter import messagebox

Step 3: Create the main game window
Next, we will create the main game window and set its title and size. Add the following code to create a basic window:

root = tk.Tk()
root.title("Guess the Random Number Game")
root.geometry("300x200")

Step 4: Generate a random number
We will generate a random number between 1 and 100 using the random.randint() function. Add the following code to create a random number variable:

random_number = random.randint(1, 100)

Step 5: Define the game logic
Next, we will define the game logic by creating a function that will check if the player’s guess is correct. Add the following code to create the check_guess() function:

def check_guess():
    guess = int(entry.get())

    if guess == random_number:
        messagebox.showinfo("Congratulations", f"You guessed the correct number: {random_number}")
        root.destroy()
    elif guess < random_number:
        messagebox.showinfo("Try Again", "Try a higher number")
    else:
        messagebox.showinfo("Try Again", "Try a lower number")

Step 6: Create the input box and submit button
We will create an input box for the player to enter their guess and a submit button to submit their guess. Add the following code to create the input box and submit button:

label = tk.Label(root, text="Enter your guess:")
label.pack()

entry = tk.Entry(root)
entry.pack()

submit_btn = tk.Button(root, text="Submit", command=check_guess)
submit_btn.pack()

Step 7: Run the main game loop
Finally, we will run the main game loop by calling the root.mainloop() function. Add the following code at the end of your script to start the game:

root.mainloop()

Congratulations! You have successfully created a ‘Guess the Random Number’ game using Python and Tkinter. You can further enhance the game by adding features like keeping track of the number of attempts, setting a time limit, or adding sound effects. Have fun playing and customizing the game!