Number Guessing Game Using Python Tkinter Module
Last Updated : 28 Apr, 2025
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
Resources used in this project:
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
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 :
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