Creating a Fun ‘Guess the Number’ Game with Tkinter in Python

Creating a simple fun game ‘Guess the Number’ with the help of  Python Tkinter. Python Tkinter it’s a library of Python by importing we can make the graphical user interface (GUI). Python Tkinter (GUI) is the fastest and easiest way to create GUI. In this tutorial, we’ll walk you through the process of building a “Guess the Number” game using Python and Tkinter. This project is perfect for beginners who want to explore GUI programming and developers looking to practice and brush up on their Python skills.

The “Guess the Number” game is a challenge where players attempt to guess a randomly selected number within the range of (1 to 100). With each guess, the system will give feedback. This simple logic makes it an ideal project to practice control flow, user input handling, and basic GUI design by using Python and Tkinter.

‘Guess the Number’ Game with Tkinter!

The Game rule will be:

You will get ten attempts and you have to guess the number between one to hundred. To play the Number Quest: Guess the Secret Number game, first, you have to enter a number between 0 and 100 in the input field. If your guess is correct, you will see the message: “Congratulations! Your guessing number is the correct answer.” If your guess is wrong, you will see it is higher or lower than the correct number. Based on this feedback, enter a new guess and submit it again. You have a total of 10 attempts to guess the correct number. If you think the number correctly within 10 attempts, you win! If you use up all 10 attempts without guessing the correct number, the game will show: “You lost.” Enjoy the challenge and have fun guessing!

Steps for creating the game and code Explanations:

Here we have written the code using Python language.

Importing Libraries :
from tkinter import *  # We are importing the tkinter for GUI application making
import random       # This for importing random values
  • “tkinter” is a standard GUI library of Python.
  • “random” is used to generate a random number
Setting Up the Main Window :
window = Tk()
window.title("Number_Guessing")
window["bg"] = "red"
window.geometry("510x390")
  • ‘Tk()’  initializes the Tkinter window.
  • ‘title’ sets the title of the window.
  • ‘bg’ sets the background color of the window to red or it can be any color.
  • ‘geometry’ sets the size of the window that will face the interface.
Initializing Variables :
ran_Num = random.randint(0, 100)
chances = 10
Var_iable = IntVar()
display = StringVar()  # StringVar() is used for Label
  • ‘ran_Num’ stores a random number between 0 and 100 and the number range can be different.
  • ‘chances’ By this, we count the no of attempts he or she is taking.
  • ‘IntVar()’ is used to store the user input as an integer.
  • ‘StringVar()’ is used to update the display label dynamically.
Function creating to Check the Guess :
def checking_guess():
    global ran_Num
    global chances

    user_input = Var_iable.get()
    if chances > 0:
        if user_input == ran_Num:
            msg = f"Congratulations! Your guess {ran_Num} is the correct answer."
        elif user_input > ran_Num:
            chances -= 1
            msg = f"{user_input} is too high. You have {chances} attempts left."
        elif user_input < ran_Num:
            chances -= 1
            msg = f"{user_input} is too low. You have {chances} attempts left."
        else:
            msg = "Something went wrong."
    else:
        msg = f"You lost! No attempts left. The correct number was {ran_Num}."

    display.set(msg)
  •  ‘global’ is used to modify ‘ran_Num’ and ‘chances’ variables inside the function.
  • ‘user_input’ gets the value entered by the user which can be any integer value.
  • ‘chances’ check how many attempts are left.
  • It compares ‘user_input’ with ‘ran_Num’ to determine if the guess is correct or not.
  • ‘display.set(msg)’ updates the message displayed on the GUI.
Setting Up the GUI Components :
# Title label
lab1 = Label(
    window,
    text="Number Guessing Game",
    font=("sans-serif", 24, "bold"),
    relief=SUNKEN,
    padx=12, pady=12,
    bg="green"
)
lab1.pack(pady=(30, 0))
  • ‘Label’ creates a label widget.
  • ‘text’ sets the text of the label.
  • ‘font’ sets the font style, size, and weight.
  • ‘relief’ provides a 3D effect to the label.
  • ‘padx’ and ‘pady’ add padding around the text.
  • ‘bg’ sets the background color.
  • ‘pack’ places the label on the window.
# Entry widget for user input
ent = Entry(
    window,
    textvariable=Var_iable,
    font=("Times New Roman", 18),
)
ent.pack(pady=(51, 12))
  • ‘Entry’ creates an entry widget for user input.
  • ‘textvariable’ links the entry widget to the ‘Var_iable’.
# Button to submit the guess
buton = Button(
    window,
    text="Submit Guess",
    bg="pink",
    font=("sans-serif", 18),
    command=checking_guess
)
buton.pack()
  • ‘Button’ creates a button widget.
  • ‘command’ links the button to the ‘checking_guess’ function.
# Label to display messages
lab2 = Label(
    window,
    textvariable=display,
    bg="#5671A6",
    font=("sans-serif", 18)
)
lab2.pack(pady=(20, 0))
  • ‘textvariable’ links the label to the ‘display’ variable to show dynamic messages.
Running the Main Loop :
window.mainloop()  # This starts the GUI event loop
  • ‘mainloop()’ runs the Tkinter event loop, making the window responsive to user inputs.
The entire Code is :
from tkinter import *  # We are importing the tkinter for GUI application making
import random       # This for importing random values
window = Tk()
window.title("Number_Guessing") 
window["bg"]="red"
window.geometry("510x390")

ran_Num = random.randint(0,100)
chances = 10
Var_iable = IntVar()
display = StringVar()   # Here StringVar() is for Label


def checking_guess():
    # Here we are using the global because our variable is outside of the function
    global ran_Num
    global chances
 
    # Here we are using normal if else condition
    user_input = Var_iable.get()
    if chances > 0:
        if user_input == ran_Num:
            msg = f"Congratulations your guessing number {ran_Num} is the correct answer"

        elif user_input > ran_Num:
            chances -= 1
            msg = f"{user_input} is greater number.Now you have {chances} attempt left"

        elif user_input < ran_Num:
            chances -= 1
            msg = f"{user_input} is smaller number.Now you have {chances} attemp left"

        else:
            msg = "something went wrong"
    
    else:
        msg = f"You Lost(Next time better luck)! you have {chances} attempt left"

    display.set(msg)  # for Display 

# GUI PART START FROM HERE

# This Label widget implements a display box where we can place text or images.....
lab1=Label(
        window,
        text = "Number Guessing Game",
        font = ("sans-serif",24,"bold"),
        #relief=SOLID,
        relief = SUNKEN,   # The relief style of a widget refers to certain simulated 3-D effects around the outside of the widget...
        padx = 12,pady=12,
        bg = "green")
lab1.pack(pady=(30,0))

# The Entry Widget is a Python Tkinter Widget used to Enter or display a single line of text

ent=Entry(
    window,
    textvariable = Var_iable,
    font = ("The New Roman",18),
    )
ent.pack(pady=(51,12))

# It's make the button here we make the "Submit Guess" button by using this

buton=Button(
        window,
        text = "Submit Guess",
        bg = "pink",
        font = ("sans-serif",18),
        command = checking_guess
        )
buton.pack()

# Another label 

lab2=Label(
    window,
    textvariable=display,
    bg = "#5671A6",
    font = ("sans-serif",18)
  )
lab2.pack(pady=(20,0))

window.mainloop()  # This for showing the interface
After running the code it will give the output :

 

 

Video Link in the form of GIF Gif Video

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top