Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Number Guessing Game Using Python Tkinter Module
Next article icon

Number Guessing Game Using Python Tkinter Module

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Number Guessing Game using the Python Tkinter module is a simple game that involves guessing a randomly generated number. The game is developed using the Tkinter module, which provides a graphical user interface for the game. The game has a start button that starts the game and a text entry field where the user can enter their guess. The game also has a status label that displays the game status, such as "Too High", "Too Low", or "Correct". If the user enters the correct number, a message is displayed indicating that they have won the game. If the user fails to guess the number, the game restarts automatically, generating a new number to be guessed. The game continues until the user wins. The game is designed to be simple and user-friendly, making it an ideal project for beginners to learn the basics of the Python Tkinter module and game development.

Rules of Games

  • You are given only 10 attempts to guess the number.
  • The number generated randomly with each attempt your score will going to reduce.

The language used

Python

Resources used in this project: 

  • guess.png
  • bt.png
  • score.txt

Steps to create a project

Step 1.

 Install and Import all required modules which are PIL (Pillow), and Tkinter. Tkinter provides a graphical user interface where we are going to develop a UI for users.

pip install tk  pip install Pillow
Python
from tkinter import * from PIL import ImageTk,Image import random import tkinter.messagebox as tmsg 

Step 2.

 Create a function to generate a number

Python3
def generate():     global comp     comp=random.randint(1, 101) 

Here We are using the randint function of Python to generate the random number between 1 and 100.

Step 3.  

Defining function which will have all configuration of UI screen - title, the geometry of screen, min and max size, etc.

Python
def basic():     # setup the window size, title, logo     app.title("Number Guessing game")     app.geometry("500x500")     app.minsize(500, 500)     app.maxsize(500, 500)     photo = PhotoImage(file="guess.png")     app.iconphoto(False, photo)     heading = Label(text='Number Guessing game', font="Helvicta 18 bold",                     bg='black', fg='tomato', padx=170).pack()     with open('score.txt', 'r') as f:         hg = f.read()     sc = Label(app, text=f'Previous score: {hg}', font='lucida 8 bold ').pack(         anchor=E, padx=25, pady=5)      # footer     footer = Label(text='Developed by Siddharth Dyamgond', font="Helvicta 8 bold",                    bg='black', fg='tomato', padx=153).pack(side=BOTTOM)      # Setup Menu     mymenu = Menu(app)     filee = Menu(mymenu, tearoff=0)     mymenu.add_cascade(label='Start', menu=filee)     mymenu.add_cascade(label='Restart', command=restart)     mymenu.add_command(label='About', command=call1)     mymenu.add_command(label='Quit', command=quit)     app.config(menu=mymenu)     generate() 

The geometry () function is used to set the size of the Main Window

Step 4. 

Initializing the screen by calling the constructor of Tkinter TK() and taking user input from the user 

Python
app = Tk() basic() count = 0 comp = random.randint(1, 101)  # generating random values between 1 to 100 userv = StringVar()  # variable to getting input in string format  # creating input field user = Entry(app, textvariable=userv, justify=CENTER, relief=FLAT,              borderwidth=2, font='Helvicta 18 bold').pack(pady=10)  # submit button i = Image.open('bt.jpg') resized_image = i.resize((150, 50), Image.ANTIALIAS) new_image = ImageTk.PhotoImage(resized_image) submit = Button(app, image=new_image, command=result,                 font='Helvicta 18 bold', relief=FLAT).pack(pady=10) show = Label(app, text='', font='Helvicta 12 bold') show.pack(pady=10) 

The Button Function is used to submit the guessed value by the user.

Step 5.  

Declaring result function which will validate the user input and display message according to user input.

Python
def result():     global count     number=userv.get()     if number=='':         tmsg.showerror('Error',"Please enter a value")     else:         n=int(number)         count+=1         if count==10:             a=tmsg.showinfo('Game over','You loose the Game!')         elif comp==n:             score=11-count             a=tmsg.showinfo('Win',f'You guess right number!\nYour score {score}')             show.config(text='Winn!',fg='green')             with open('score.txt','w') as f:                 f.write(str(score))             generate()             tmsg.showinfo('Next number',f'click ok to Guess another number')         elif comp>n:             show.config(text='Select greater number',fg='red')         else:             show.config(text='Select smaller number',fg='red') 

This Function is doing logical calculations and shows the dialog box according to conditions.

Here Open Function is used to write a score of the user if he guessed correctly.

Step 6. 

Creating a reset function to restart our game

Python3
def restart():     tmsg.showerror('Reset',"Game reset!")     generate() 

This function shows a dialog box to the user of a particular message. Then restart it again.

Step 7.  

Finally initialized game using the main loop () function.

Python
app.mainloop() 

Final Code :

Python3
from tkinter import * from PIL import ImageTk, Image import random import tkinter.messagebox as tmsg  app = Tk() count = 0   def generate():     global comp     comp = random.randint(1, 101)   def basic():     # setup the window size, title, logo     app.title("Number Guessing game")     app.geometry("500x500")     app.minsize(500, 500)     app.maxsize(500, 500)     photo = PhotoImage(file="guess.png")     app.iconphoto(False, photo)     heading = Label(text='Number Guessing game', font="Helvicta 18 bold",                     bg='black', fg='tomato', padx=170).pack()     with open('score.txt', 'r') as f:         hg = f.read()     sc = Label(app, text=f'Previous score: {hg}', font='lucida 8 bold ').pack(         anchor=E, padx=25, pady=5)      # footer     footer = Label(text='Developed by Siddharth Dyamgond', font="Helvicta 8 bold",                    bg='black', fg='tomato', padx=153).pack(side=BOTTOM)      # Setup Menu     mymenu = Menu(app)     filee = Menu(mymenu, tearoff=0)     mymenu.add_cascade(label='Start', menu=filee)     mymenu.add_cascade(label='Restart', command=restart)     mymenu.add_command(label='About', command=call1)     mymenu.add_command(label='Quit', command=quit)     app.config(menu=mymenu)     generate()   def result():     global count     number = userv.get()     if number == '':         tmsg.showerror('Error', "Please enter a value")     else:         n = int(number)         count += 1         if count == 10:             a = tmsg.showinfo('Game over', 'You loose the Game!')         elif comp == n:             score = 11-count             a = tmsg.showinfo(                 'Win', f'You guess right number!\nYour score {score}')             show.config(text='Winn!', fg='green')             with open('score.txt', 'w') as f:                 f.write(str(score))             generate()             tmsg.showinfo('Next number', f'click ok to Guess another number')         elif comp > n:             show.config(text='Select greater number', fg='red')         else:             show.config(text='Select smaller number', fg='red')   def restart():     tmsg.showerror('Reset', "Game reset!")     generate()   def call1():     str1 = 'This game is developed by XD\n\ncopyright@2021-22 '     tmsg.showinfo('About', str1)   basic()  print(comp) userv = StringVar() user = Entry(app, textvariable=userv, justify=CENTER, relief=FLAT,              borderwidth=2, font='Helvicta 18 bold').pack(pady=10) i = Image.open('guess.png', mode='r') img = ImageTk.PhotoImage(i) l = Label(image=img).pack(pady=30) i = Image.open('bt.png') resized_image = i.resize((150, 50), Image.ANTIALIAS) new_image = ImageTk.PhotoImage(resized_image) submit = Button(app, image=new_image, command=result,                 font='Helvicta 18 bold', relief=FLAT).pack(pady=10) show = Label(app, text='', font='Helvicta 12 bold') show.pack(pady=10) app.mainloop() 

Output:

Final Output Screen

Video output :


Next Article
Number Guessing Game Using Python Tkinter Module

S

siddyamgond
Improve
Article Tags :
  • Python
  • Python Tkinter-projects
Practice Tags :
  • python

Similar Reads

    Number Guessing Game Using Python Streamlit Library
    The game will pick a number randomly from 1 to 100 and the player needs to guess the exact number guessed by calculating the hint. The player will get 7 chances to guess the number and for every wrong guess game will tell you if the number is more or less or you can take a random hint to guess the n
    4 min read
    Snake Game in Python - Using Pygame module
    Snake game is one of the most popular arcade games of all time. In this game, the main objective of the player is to catch the maximum number of fruits without hitting the wall or itself. Creating a snake game can be taken as a challenge while learning Python or Pygame. It is one of the best beginne
    15+ min read
    Python - Dynamic GUI Calculator using Tkinter module
    Python provides many options for developing GUI like Kivy, PyQT, WxPython, and several others. Tkinter is the one that is shipped inbuilt with python which makes it the most commonly used out of all. Tkinter is easy, fast, and powerful.  Beginners can easily learn to create a simple calculator using
    3 min read
    Color game using Tkinter in Python
    TKinter is widely used for developing GUI applications. Along with applications, we can also use Tkinter GUI to develop games. Let's try to make a game using Tkinter. In this game player has to enter color of the word that appears on the screen and hence the score increases by one, the total time to
    4 min read
    Language Detection in Python using Tkinter
    Prerequisite: Tkinter In this article, we will learn about language detection Using Python in Tkinter. In Simple Words, language identification is the problem of determining which natural language given content is in. Modules UsedTkinter module is used in Python to create GUI based interfaces.For La
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences