Create a Number Guessing Game with Tkinter in Python

Faraz

By Faraz -

Learn how to create a fun number guessing game using Tkinter in Python. This step-by-step guide covers everything from setting up your environment to adding game logic.


create-a-number-guessing-game-with-tkinter-in-python.webp

Table of Contents

  1. Setting Up Your Development Environment
  2. Full Number Guessing Game Source Code
  3. Explanation of Number Guessing Game Source Code
  4. Testing and Debugging
  5. Conclusion

Creating a number guessing game is a great way to learn Python programming and GUI development with Tkinter. This tutorial will guide you through the process of building a simple yet interactive game where users guess a randomly generated number. By the end of this tutorial, you'll have a solid understanding of Tkinter basics and how to implement game logic in Python.

1. Setting Up Your Development Environment

Before we start coding, it's essential to set up the development environment. First, ensure you have Python installed on your system. You can download it from the official Python website. Next, we'll use the Tkinter library, which comes pre-installed with Python. Open your terminal or command prompt and verify the installation by typing python and then import tkinter. If there are no errors, you're ready to proceed.

2. Full Number Guessing Game Source Code

import random
import tkinter as tk
from tkinter import messagebox

class NumberGuessGame(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Number Guessing Game")
        self.geometry("300x250")

        self.secret_number = random.randint(1, 100)
        self.attempts = 0
        self.max_attempts = 10  # Maximum number of attempts allowed

        self.label = tk.Label(self, text="Guess a number between 1 and 100:")
        self.label.pack(pady=10)

        self.entry = tk.Entry(self)
        self.entry.pack(pady=5)

        self.button = tk.Button(self, text="Guess", command=self.check_guess)
        self.button.pack(pady=10)

        self.info_label = tk.Label(self, text=f"You have {self.max_attempts} attempts remaining.")
        self.info_label.pack(pady=5)

        self.reset_button = tk.Button(self, text="Reset", command=self.reset_game)
        self.reset_button.pack(pady=10)

    def check_guess(self):
        try:
            guess = int(self.entry.get())
            self.attempts += 1
            remaining_attempts = self.max_attempts - self.attempts

            if guess < self.secret_number:
                messagebox.showinfo("Result", "Too low! Try again.")
            elif guess > self.secret_number:
                messagebox.showinfo("Result", "Too high! Try again.")
            else:
                messagebox.showinfo("Congratulations!",
                                    f"You guessed the number {self.secret_number} in {self.attempts} attempts!")
                self.reset_game()
                return

            if remaining_attempts > 0:
                self.info_label.config(text=f"You have {remaining_attempts} attempts remaining.")
            else:
                messagebox.showinfo("Game Over",
                                    f"Sorry, you ran out of attempts. The number was {self.secret_number}.")
                self.reset_game()

        except ValueError:
            messagebox.showerror("Error", "Invalid input. Please enter a valid number.")

    def reset_game(self):
        self.secret_number = random.randint(1, 100)
        self.attempts = 0
        self.label.config(text="Guess a number between 1 and 100:")
        self.info_label.config(text=f"You have {self.max_attempts} attempts remaining.")
        self.entry.delete(0, tk.END)


if __name__ == "__main__":
    app = NumberGuessGame()
    app.mainloop()

3. Explanation of Number Guessing Game Source Code

Imports and Initialization:

  • random: Imported for generating random numbers.
  • tkinter: Used for creating the GUI application.
  • messagebox: Part of tkinter used to display messages.

NumberGuessGame Class:

  • Inherits from tk.Tk, which makes it a tkinter application.
  • __init__ method: Sets up the initial GUI with a title, size, and initializes game variables:
    • secret_number: Random number between 1 and 100.
    • attempts: Counter for the number of attempts made.
    • max_attempts: Maximum number of attempts allowed (here set to 10).
    • Creates labels, entry field for user input, buttons for guessing and resetting, and labels for displaying information.

check_guess method:

  • Called when the "Guess" button is clicked.
  • Retrieves user input from self.entry.
  • Validates the input:
  • If valid (converts to integer successfully):
    • Increments self.attempts.
    • Compares guess with self.secret_number and displays appropriate message boxes ("Too low", "Too high", or "Congratulations").
    • Updates self.info_label to show remaining attempts or declares "Game Over" if no attempts remain.
  • If invalid input (ValueError), displays an error message.

reset_game method:

  • Resets the game:
    • Generates a new self.secret_number.
    • Resets self.attempts to 0.
    • Updates GUI labels (self.label and self.info_label) and clears the entry field (self.entry).

Main Application Loop:

  • Checks if the script is run directly (__name__ == "__main__").
  • Creates an instance of NumberGuessGame.
  • Starts the tkinter main event loop (mainloop()), which waits for user input and responds to events.

How to Play:

  1. Enter your guess into the entry field and click "Guess".
  2. You'll receive feedback on whether your guess was too high, too low, or correct.
  3. The game tracks your remaining attempts.
  4. If you guess the number correctly within the allowed attempts, you win!
  5. Use the "Reset" button to start a new game at any time.

4. Testing and Debugging

Testing is crucial to ensure your game works as expected. Test different scenarios, such as entering non-numeric values, guessing too high or too low, and verifying the feedback messages. Debug any issues by checking the logic in the check_guess and reset_game functions. Use print statements or a debugger to trace the values of variables and ensure the game flow is correct.

5. Conclusion

Creating a number guessing game using Tkinter in Python is a fun and educational project. It helps you learn the basics of GUI programming and game logic implementation. By following this guide, you should now have a working game that you can further enhance with additional features. Keep experimenting and improving your skills by building more complex projects.

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺