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 download from here:
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:
Video output :