Number Guessing Game in Python (With GUI)
In this tutorial, we will build a simple number guessing game using Python with a graphical user interface.
The program generates a random number, and the user tries to guess it with hints provided after each attempt.
1. Requirements
Make sure Python is installed on your system.
Download Python: https://www.python.org/downloads/
2. Steps to Run the Project
Step 1: Install Python IDE.
Step 2: Copy and paste the code into your IDE.
Step 3: Run the program.
Step 4: Enter your guess in the input box.
Step 5: Get hints (Too High / Too Low) until you guess correctly.
3. Python Code
import tkinter as tk
import random
number = random.randint(1, 100)
def check_guess():
try:
guess = int(entry.get())
if guess < number:
result_label.config(text="Too Low!")
elif guess > number:
result_label.config(text="Too High!")
else:
result_label.config(text="Correct! You guessed it!")
except ValueError:
result_label.config(text="Enter a valid number")
def reset_game():
global number
number = random.randint(1, 100)
result_label.config(text="Game Reset! Guess again.")
entry.delete(0, tk.END)
root = tk.Tk()
root.title("Number Guessing Game")
instruction = tk.Label(root, text="Guess a number between 1 and 100")
instruction.pack()
entry = tk.Entry(root)
entry.pack()
check_btn = tk.Button(root, text="Check", command=check_guess)
check_btn.pack()
reset_btn = tk.Button(root, text="Reset", command=reset_game)
reset_btn.pack()
result_label = tk.Label(root, text="Start guessing...")
result_label.pack()
root.mainloop()
4. Output
A GUI window appears where users can input their guess.
The program gives hints like 'Too High' or 'Too Low' until the correct number is guessed.
Users can reset the game to play again.
Conclusion
This project helps in understanding random numbers, conditional logic, and GUI development.
It is a fun beginner-friendly game to practice Python programming.
Codecrown