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:
- Label to display instructions.
- Entry widget for the player to input their guess.
- Button to submit the guess.
- 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:
- 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.
- Random Number:
- The game generates a random number between 1 and 100 when the window is launched.
- 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.
- The check_guess() function checks the player's guess and gives feedback through the feedback_label:
- Disabling Input:
- Once the player guesses the number correctly, the guess button is disabled to prevent further input.
Example Game Flow:
- The user guesses 50. The feedback is “Too low! Try again.”
- The user guesses 75. The feedback is “Too high! Try again.”
- The user guesses 62. The feedback is “Correct! You guessed it in 3 attempts.”
- 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:
- Change the Range: You can change the range of random numbers to make the game easier or harder by modifying random.randint(1, 100).
- Add Restart Button: Add a button to restart the game after the user guesses correctly.
- 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.