Home » Higher-Lower Game in Python using Tkinter

Higher-Lower Game in Python using Tkinter

Java SE 11 Programmer I [1Z0-815] Practice Tests
1 Year Subscription
Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
Spring Framework Basics Video Course
Oracle Java Certification

In a previous project we created a Higher lower guessing game which you played on the command line, lets make a gui version.

In this tutorial, we will create a Higher-Lower Game using Python and the Tkinter library. The game will involve:

  • A graphical user interface (GUI) where the player can input a guess.
  • The computer selecting a random number between a predefined range (e.g., 1 to 100).
  • The program giving feedback on whether the guess is too high or too low.
  • The game continuing until the player guesses the correct number.

Let's break the game into steps to create the GUI and game logic.

Step 1: Import the Required Modules

We will import:

  • tkinter for creating the GUI.
  • random for generating the random number for the game.
import tkinter as tk
import random

Step 2: Create the Tkinter Window

The first step is to create the main window for the game. We will set the window title, size, and background color.

# Create the main Tkinter window
root = tk.Tk()
root.title("Higher-Lower Game")
root.geometry("400x300")  # Set the window size
root.configure(bg="lightblue")  # Set background color

Step 3: Define the Game Logic

We will now define the game logic, including:

  • Generating the random number.
  • Handling user guesses.
  • Providing feedback to the user on whether the guess is too high, too low, or correct.

The game starts by generating a random number when the window is created.

# Generate a random number between 1 and 100
random_number = random.randint(1, 100)

# Variable to keep track of the number of attempts
attempts = 0

Step 4: Create GUI Widgets

We will create several widgets:

  1. Label to display instructions.
  2. Entry widget for the player to input their guess.
  3. Button to submit the guess.
  4. Label to display feedback on the guess (e.g., “Too high” or “Too low”).
# Create a label to show instructions
instructions_label = tk.Label(root, text="Guess a number between 1 and 100", font=("Arial", 14), bg="lightblue")
instructions_label.pack(pady=20)

# Create an Entry widget for user input
guess_entry = tk.Entry(root, font=("Arial", 14))
guess_entry.pack(pady=10)

# Create a label to display feedback
feedback_label = tk.Label(root, text="", font=("Arial", 12), bg="lightblue")
feedback_label.pack(pady=10)

Step 5: Define a Function to Handle User Input

We will define a function called check_guess() that gets the player's guess, checks it against the random number, and provides feedback. The function will also track the number of attempts.

# Function to check the user's guess
def check_guess():
    global attempts
    attempts += 1  # Increment the number of attempts

    try:
        # Get the user's guess from the Entry widget
        guess = int(guess_entry.get())

        # Check if the guess is too high, too low, or correct
        if guess < random_number:
            feedback_label.config(text="Too low! Try again.")
        elif guess > random_number:
            feedback_label.config(text="Too high! Try again.")
        else:
            feedback_label.config(text=f"Correct! You guessed it in {attempts} attempts.")
            guess_button.config(state="disabled")  # Disable the button after correct guess
    except ValueError:
        feedback_label.config(text="Please enter a valid number.")

Explanation:

  • The player's input is retrieved from the guess_entry widget.
  • The guess is compared with the random number, and feedback is provided through the feedback_label.
  • If the guess is correct, the button is disabled, and a congratulatory message is displayed.

Step 6: Create a Button to Submit the Guess

We will add a Button widget that the player clicks to submit their guess. This button will call the check_guess() function to evaluate the guess.

# Create a button to submit the guess
guess_button = tk.Button(root, text="Submit Guess", font=("Arial", 14), command=check_guess)
guess_button.pack(pady=10)

Step 7: Start the Tkinter Main Event Loop

Finally, we start the Tkinter event loop to keep the window open and responsive to user input.

# Run the Tkinter main loop
root.mainloop()

Complete Python Code for Higher-Lower Game with Tkinter

Here is the complete code for the Higher-Lower Game using Tkinter:

import tkinter as tk
import random

# Create the main Tkinter window
root = tk.Tk()
root.title("Higher-Lower Game")
root.geometry("400x300")  # Set the window size
root.configure(bg="lightblue")  # Set background color

# Generate a random number between 1 and 100
random_number = random.randint(1, 100)

# Variable to keep track of the number of attempts
attempts = 0

# Create a label to show instructions
instructions_label = tk.Label(root, text="Guess a number between 1 and 100", font=("Arial", 14), bg="lightblue")
instructions_label.pack(pady=20)

# Create an Entry widget for user input
guess_entry = tk.Entry(root, font=("Arial", 14))
guess_entry.pack(pady=10)

# Create a label to display feedback
feedback_label = tk.Label(root, text="", font=("Arial", 12), bg="lightblue")
feedback_label.pack(pady=10)

# Function to check the user's guess
def check_guess():
    global attempts
    attempts += 1  # Increment the number of attempts

    try:
        # Get the user's guess from the Entry widget
        guess = int(guess_entry.get())

        # Check if the guess is too high, too low, or correct
        if guess < random_number:
            feedback_label.config(text="Too low! Try again.")
        elif guess > random_number:
            feedback_label.config(text="Too high! Try again.")
        else:
            feedback_label.config(text=f"Correct! You guessed it in {attempts} attempts.")
            guess_button.config(state="disabled")  # Disable the button after correct guess
    except ValueError:
        feedback_label.config(text="Please enter a valid number.")

# Create a button to submit the guess
guess_button = tk.Button(root, text="Submit Guess", font=("Arial", 14), command=check_guess)
guess_button.pack(pady=10)

# Run the Tkinter main loop
root.mainloop()

How the Game Works:

  1. User Interface:
    • A window is created with a label for instructions, an entry box for guesses, a button to submit the guess, and a label to display feedback.
  2. Random Number:
    • The game generates a random number between 1 and 100 when the window is launched.
  3. Guess Evaluation:
    • The check_guess() function checks the player's guess and gives feedback through the feedback_label:
      • If the guess is too low, it prompts the user with “Too low!”
      • If the guess is too high, it prompts the user with “Too high!”
      • If the guess is correct, it congratulates the user and displays the number of attempts.
  4. Disabling Input:
    • Once the player guesses the number correctly, the guess button is disabled to prevent further input.

Example Game Flow:

  1. The user guesses 50. The feedback is “Too low! Try again.”
  2. The user guesses 75. The feedback is “Too high! Try again.”
  3. The user guesses 62. The feedback is “Correct! You guessed it in 3 attempts.”
  4. The game disables the button after the correct guess, indicating that the game is over.

Customization

Here are a few ideas to enhance or customize the game:

  1. Change the Range: You can change the range of random numbers to make the game easier or harder by modifying random.randint(1, 100).
  2. Add Restart Button: Add a button to restart the game after the user guesses correctly.
  3. Difficulty Levels: Add different difficulty levels where the range of numbers is higher for more difficult levels.

Conclusion

In this tutorial, we built a Higher-Lower Game using Python and Tkinter.

The game features a graphical interface where users can input their guesses and receive feedback on whether the guess is too high or too low.

The game continues until the user guesses correctly, and the interface is simple and easy to extend.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More