Python Tutorial – Make a GUI Number Guessing Game with Tkinter

Hi Welcome to this new tutorial from MOO ICT. Here we will be making a number guessing game using python and tkinter. The main feature of this game is that it will have 3 clickable buttons, each button will display random number. The computer will have a secret number variable that will contain one of the buttons random number. User will need to click on the right button to guess the computers secret number. If they do it will display a text to say you guessed it correctly if not you can continue to play. I didn’t do an end to this game on purpose so you can make it or end it anyway you want to.

Lesson objective’s –

  1. Make a number guessing game with Python and Tkinter
  2. Use multiple GUI components in the game
  3. Add buttons to lists
  4. Use random to pick a random button and pick random numbers for the buttons
  5. Use local and global variables
  6. Use functions and Events in the game

Video Tutorial –


Source Code –

from tkinter import *
import random

root = Tk()
root.title("MOO ICT")

secret_number = "none"

# function and events

def StartGame():
    global secret_number

    for button in button_list:
        button.config(text=str(random.randint(0, 100)))
    randomButton = random.choice(button_list)

    secret_number = randomButton.cget("text")

    print("Secret Number is: ", secret_number)

def OnClick(event):
    btn = event.widget
    buttonText = btn.cget("text")

    if secret_number == buttonText:
        answer_label.config(text="Yes it was " + secret_number)

# gui components

title_label = Label(root, text="Guess the Secret Number", font=("Helvetical 12"), pady = 8, justify="center")
button_one = Button(root, text="00", font=("Helvetical 15"), width=6, pady=15, bg="palegreen")
button_two = Button(root, text="00", font=("Helvetical 15"), width=6, pady=15, bg="skyblue")
button_three = Button(root, text="00", font=("Helvetical 15"), width=6, pady=15, bg="coral")

button_list = [button_one, button_two, button_three]

answer_label = Label(root, text="Answer", font=("Helvetical 15"), pady=9, fg="purple", justify="center")

title_label.grid(row = 0, column=0, columnspan=3)
button_one.grid(row=1, column=0)
button_two.grid(row=1, column=1)
button_three.grid(row=1, column=2)
answer_label.grid(row = 2, column=0, columnspan=3)

button_one.bind("<Button-1>", OnClick)
button_two.bind("<Button-1>", OnClick)
button_three.bind("<Button-1>", OnClick)





Comments are closed.