2025년 3월 19일 수요일

Python Number Guessing Game (GUI) - Tkinter Tutorial & Code

 




import tkinter as tk
import random
from tkinter import messagebox

def check_guess():
    """Checks the user's guess against the answer."""
    global guesses_taken
    guesses_taken += 1

    try:
        guess = int(guess_entry.get())
    except ValueError:
        messagebox.showerror("Error", "Please enter a valid number.")
        return

    if guess < answer:
        result_label.config(text="Too low!")
    elif guess > answer:
        result_label.config(text="Too high!")
    else:
        result_label.config(text=f"Congratulations! You guessed the number in {guesses_taken} guesses!")
        guess_button.config(state=tk.DISABLED)  # Disable the button after winning
        guess_entry.config(state=tk.DISABLED)  # Disable the entry field

def new_game():
    """Starts a new game."""
    global answer, guesses_taken
    answer = random.randint(1, 100)
    guesses_taken = 0
    result_label.config(text="")
    guess_entry.delete(0, tk.END)  # Clear the entry field
    guess_button.config(state=tk.NORMAL)  # Enable the button
    guess_entry.config(state=tk.NORMAL)  # Enable the entry field

# --- Main Window Setup ---
window = tk.Tk()
window.title("Number Guessing Game")
window.geometry("400x200")  # Set window size

# --- Widgets ---
instruction_label = tk.Label(window, text="Guess a number between 1 and 100:")
instruction_label.pack(pady=10)

guess_entry = tk.Entry(window)
guess_entry.pack()

guess_button = tk.Button(window, text="Guess", command=check_guess)
guess_button.pack(pady=5)

result_label = tk.Label(window, text="")
result_label.pack()

new_game_button = tk.Button(window, text="New Game", command=new_game)
new_game_button.pack(pady=10)

# --- Initialize Game ---
answer = random.randint(1, 100)
guesses_taken = 0

window.mainloop()

-----------------------------------------------------------------------------------------

How to Run:

  1. Save the Code: Copy the code above and save it as a .py file (e.g., number_guessing_game.py).

  2. Run:

    • Command Prompt or PowerShell:

      • Navigate to the directory where you saved the file.

      • Type python number_guessing_game.py and press Enter.

    • IDLE (Python GUI):

      • Open IDLE.

      • Go to File > Open and open the Python file you saved.

      • Select Run > Run Module or press F5.

Code Explanation:

  • import random: Imports the random module to generate random numbers.

  • number_guessing_game() function: Contains the main logic of the game.

  • random.randint(1, 100): Generates a random integer between 1 and 100 (inclusive).

  • input("Enter your guess: "): Prompts the user to enter a guess.

  • int(): Converts the input string to an integer. Includes ValueError exception handling to display an error message for invalid input.

  • if/elif/else: Checks if the user's guess is too low, too high, or correct.

  • while True: Continues the loop until the user guesses the correct number.

  • break: Exits the loop when the correct number is guessed.

  • if __name__ == "__main__":: Ensures that the number_guessing_game() function is called only when the script is executed directly.



댓글 없음:

댓글 쓰기

Recommended Posts

Troubleshooting: "Failed to find networks" Error in AUTOMATIC1111 with LoRA Files

  Troubleshooting: "Failed to find networks" Error in AUTOMATIC1111 with LoRA Files This "Failed to find networks" error...