|
| 1 | +import tkinter as tk |
| 2 | +from tkinter import messagebox |
| 3 | +import random |
| 4 | +import sys # Import the sys module for exiting the application |
| 5 | + |
| 6 | +# Define upper and lower bounds for the game |
| 7 | +lower_limit = 1 |
| 8 | +upper_limit = 10 |
| 9 | +secret_number = random.randint(lower_limit, upper_limit) |
| 10 | + |
| 11 | +# Function to check if the user's guess is correct |
| 12 | +def check_guess(): |
| 13 | + user_guess = int(guess_entry.get()) |
| 14 | + if user_guess == secret_number: |
| 15 | + messagebox.showinfo("Congratulations", "Congratulations! You guessed it!") |
| 16 | + elif user_guess < secret_number: |
| 17 | + result_label.config(text="Try a higher number.") |
| 18 | + else: |
| 19 | + result_label.config(text="Try a lower number.") |
| 20 | + |
| 21 | +# Function to exit the application |
| 22 | +def exit_game(): |
| 23 | + root.destroy() # Close the Tkinter window and exit the application |
| 24 | + |
| 25 | +# Create the main application window |
| 26 | +root = tk.Tk() |
| 27 | +root.title("Number Guessing Game") |
| 28 | +root.geometry("400x200") |
| 29 | + |
| 30 | +# Change the background color of the window and label to salmon |
| 31 | +root.configure(bg="pink1") |
| 32 | + |
| 33 | +# Create and place widgets using grid |
| 34 | +instructions_label = tk.Label(root, text=f"Guess a number between {lower_limit} and {upper_limit}:", bg="pink1") |
| 35 | +instructions_label.grid(row=0, column=0, columnspan=2) |
| 36 | + |
| 37 | +guess_entry = tk.Entry(root) |
| 38 | +guess_entry.grid(row=1, column=0, columnspan=2) |
| 39 | + |
| 40 | +guess_button = tk.Button(root, text="Guess", command=check_guess) |
| 41 | +guess_button.grid(row=2, column=0) |
| 42 | + |
| 43 | +exit_button = tk.Button(root, text="Exit", command=exit_game) |
| 44 | +exit_button.grid(row=2, column=1) |
| 45 | + |
| 46 | +result_label = tk.Label(root, text="", bg="pink1") |
| 47 | +result_label.grid(row=3, column=0, columnspan=2) |
| 48 | + |
| 49 | +# Center-align the widgets |
| 50 | +root.grid_rowconfigure(0, weight=1) |
| 51 | +root.grid_rowconfigure(1, weight=1) |
| 52 | +root.grid_rowconfigure(2, weight=1) |
| 53 | +root.grid_rowconfigure(3, weight=1) |
| 54 | +root.grid_columnconfigure(0, weight=1) |
| 55 | +root.grid_columnconfigure(1, weight=1) |
| 56 | + |
| 57 | +# Run the main loop |
| 58 | +root.mainloop() |
0 commit comments