Kalebu Jordan

Become a Pro Python Developer

Introduction

Hello, Guys on this tutorial I will guide you to building a Desktop Guessing Game in Python using Tkinter Library.

A game will be generating a random number and then prompt a user to guess the number, and after the user enter a number if the guess is wrong, it will keep prompting till the user guess the right number.

Requirements

For those in windows, python comes with Tkinter Library by default for Linux you may need to install it manually

pip install python-tk

Building our Guessing Game

We are going to build our guessing game using object – oriented approach , we will have a single class GuessingGame which will hold everything for our game from Logic to UI .

Importing necessary modules
from random import randint
from tkinter import Label, Button, Tk, Entry
Creating Guessing game class with Initial Interface(app.py)

When we run the above code it will render an Interface of our game as shown below picture

Guessing Game Initial Interface

After Building a box to place our Game Components Let’s now add buttons, Labels, and Entry fields and place them inside our Game Canvas.

Requirements

  • Label to Attach our Question
  • Label to Attach Guessing Result
  • Entry for User to Enter Guess
  • A button to submit Guess
from random import randint
from tkinter import Label, Button, Tk, Entry

class GuessingGame:
    def __init__(self, window):
        window.title('Guessing Game')
        window.geometry('400x150')
        window.resizable(0,0)
        self.question = Label(window, font=('Times', 11))
        self.guess_result = Label(window, font=('Times', 11))
        self.entry_answer = Entry()
        self.guess_button = Button(window,text='Guess number', bg='red')
        self.question.place(x=20, y=10);self.entry_answer.place(x=120, y=50)
        self.guess_button.place(x=140, y=80);self.guess_result.place(x=100, y=120)

window = Tk()
app = GuessingGame(window)
window.mainloop()

Once you run the above code it will display the interfaces like shown below, Label for question and guess result will be configured by the game Logic

Now Let’s build function to generate a random number of particular range and also generate a Question to place in our canvas

I have made a simple function below just to do that and then I added it on the Constructor metthod

from random import randint
from tkinter import Label, Button, Tk, Entry

class GuessingGame:
    def __init__(self, window):
        window.title('Guessing Game')
        window.geometry('400x150')
        window.resizable(0,0)
        self.question = Label(window, font=('Times', 11))
        self.guess_result = Label(window, font=('Times', 11))
        self.entry_answer = Entry()
        self.guess_button = Button(window,text='Guess number', bg='red')
        self.question.place(x=20, y=10);self.entry_answer.place(x=120, y=50)
        self.guess_button.place(x=140, y=80);self.guess_result.place(x=100, y=120)
        self.new_random()
        
    def new_random(self):
        magic = lambda : randint(1, 500)
        guess_range = sorted([magic(), magic()])
        guess_text = 'I\'ve number btn {} and {} can you guess it ?'.format(guess_range[0], guess_range[1])
        self.question.configure(text = guess_text)
        self.magic_number = randint(guess_range[0], guess_range[1])
        
window = Tk()
app = GuessingGame(window)
window.mainloop()

When you run the above code it should successful generate a new random number and place a question on our game canvas as shown below

Game Logic

Now the remaining part is to add a Logic for our game, The Logic is very simple , we will get a number from the Entry box and then

  • If User number > Guess configure Guess Label as number is low
  • If User number < Guess configure Guess Label as number is high
  • If User number == Guess configure Guess Label as congratulation & Generate new random number .

I made a simple method following the above Logic and then embedded it to Guess_button so as when pressed it will render the Guess result.

Final code will look like this (game.py)
from random import randint
from tkinter import Label, Button, Tk, Entry

class GuessingGame:
    def __init__(self, window):
        window.title('Guessing Game')
        window.geometry('400x150')
        window.resizable(0,0)
        self.question = Label(window, font=('Times', 11))
        self.guess_result = Label(window, font=('Times', 11))
        self.entry_answer = Entry()
        self.guess_button = Button(window,text='Guess number', bg='red',command=self.check_guess)
        self.question.place(x=20, y=10);self.entry_answer.place(x=120, y=50)
        self.guess_button.place(x=140, y=80);self.guess_result.place(x=100, y=120)
        self.new_random()
    
    def new_random(self):
        magic = lambda : randint(1, 500)
        guess_range = sorted([magic(), magic()])
        guess_text = 'I\'ve number btn {} and {} can you guess it ?'.format(guess_range[0], guess_range[1])
        self.question.configure(text = guess_text)
        self.magic_number = randint(guess_range[0], guess_range[1])

    def check_guess(self):
        try:
            number = int(self.entry_answer.get())
            if self.magic_number>number:
                self.guess_result.configure(text = 'Your number is low ')
            elif self.magic_number<number:
                self.guess_result.configure(text='Your number is high')
            else:
                self.guess_result.configure(text='Congratulation you made it')
                self.new_random()
        except:
            pass

window = Tk()
app = GuessingGame(window)
window.mainloop()

Congratulations you have just finished complete tutorial on making your Guessing Game in Python . Check out the below video to learn out how to play it

Hope you enjoyed the Tutorial , In case of anything just drop it in the comment box below . To get full code you can check it out on My Github Profile

Don’t forget to subscribe to this blog to stay updated on upcoming Python tutorials

Leave a Reply

error

Enjoy this blog? Please spread the word :)