How to make a Hangman Game in Python – [GUI Source Code]

In this article, we will learn how to make a hangman game in python or code a hangman game in python. Also, we will make your first Python hangman GUI game that includes building a complete graphical interface like a real-time game. It’s a very fantastic project for a beginner.

How to make a Hangman Game in Python

PROJECT PREREQUISITES:

In this python project, you need to know basic python. That includes.

WHAT WILL YOU LEARN?

  • Building GUI Games using tkinter.
  • End to End development of Python game.
  • Basic Input / Output implementation.

But first, let us understand the hangman game project documentation in python by the below overview of the game.

WHAT IS THE HANGMAN GAME?

As per Wikipedia hangman game is a simple word guessing game that can initially play with two or more players. In the beginning, it was played on a paper and pencil game. A player decides on a word, phrase, or sentence in this game. The other player will try guessing it on the suggestions given by the first player in the form of letters within a word or sentence.

You can also check out the Mab libs game project, a paper and pencil game built using python.

WHAT IS THE ORIGIN OF THE GAME HANGMAN?

Throughout history, there have been many variants of this game. However, the origins of this game are still unknown many says its first variant came to light in the children’s games book assembled by Alice Gomme in 1894 named Birds, Beasts, and Fishes.

HOW DO YOU PLAY THE HANGMAN GAME?

In simple terms, the hangman game can be played with multiple players. Still, the electrical version of this game can be played with a single-player only. In standard and the most famous variant of this game, guessing the word’s letters can be played.

For example, the system will choose a word like Python. It will give you a hint like a programming language or something else, and you will have many chances to win it, and in this game, the number of losses led to man to hang.

Let’s get started with simple hangman game development using python code.

Follow to below steps to get started.

Step 1: Very first step toward any python project is to import the necessary libraries required for a particular project. So let’s import them.

import random

The random library is mainly used to generate random numbers, but it also hse many uses. 

Step 2: In this step, we will design a word list of the words the user will guess.

word_list = [‘python’, ‘tensorflow’, ‘hangman’]

Step 3: Now, we will design the hanging man and simple python user interface.

stages = ['''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========
''', '''
  +---+
  |   |
      |
      |
      |
      |
=========
''']

logo = ''' 
 _                                             
| |                                            
| |__   __ _ _ __   __ _ _ __ ___   __ _ _ __  
| '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \ 
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|
                    __/ |                      
                   |___/    '''

Step 4: Here, we will declare some required variables that we will use in the further code.

game_is_finished = False
lives = len(stages) - 1
chosen_word = random.choice(word_list)
word_length = len(chosen_word)
display = []

Step 5: Now, we will print the intro of the game by printing the logo variable.

print(logo)

Step 6: Let’s run the for loop to print the hangman we design in step 3.

for _ in range(word_length):
    display += "_"

Step 7: This is the final step and the heart of our game.

while not game_is_finished:
    guess = input("Guess a letter: ").lower()

    if guess in display:
        print(f"You've already guessed {guess}")

    for position in range(word_length):
        letter = chosen_word[position]
        if letter == guess:
            display[position] = letter
    print(f"{' '.join(display)}")

    if guess not in chosen_word:
        print(f"You guessed {guess}, that's not in the word. You lose a life.")
        lives -= 1
        if lives == 0:
            game_is_finished = True
            print("Game Over...You Lose!")

    if "_" not in display:
        game_is_finished = True
        print("You win!")

    print(stages[lives])

Now let us go through the code and understand it we are not just coping with it. We will learn the logic behind it.

Firstly a while loop checks whether the condition is true or false as we have declared the game_is_finished variable in the above steps. Then we ask users to guess and convert it to the lower case character.

We then use the if conditional statement to check whether the user has used the same word previously. If the term has been used early, we are already printing the word.

Now we are using for loop the check the position from the length of the given word. If the inputted word is correct, it will be printed and then added to the list name display we created in the beginning. And if the word is incorrect, it will print that word is not present in the target, and we will lose a life, and the hangman will add one step in the terminal.

If we are successfully guessing the target word without losing all our lives, we will win the game and change the value of game_is_finished from False to True to end the game.

We have completed our python hangman project and learned it in-depth now it’s time to execute our project.

The output of the above project will be as follow.

 _                                            
| |                                           
| |__   __ _ _ __   __ _ _ __ ___   __ _ _ __ 
| '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|
                    __/ |                     
                   |___/   
Guess a letter: g
_ _ _ _ _ _
You guessed g, that's not in the word. You lose a life.

  +---+
  |   |
  O   |
      |
      |
      |
=========

Guess a letter: d
_ _ _ _ _ _
You guessed d, that's not in the word. You lose a life.

  +---+
  |   |
  O   |
  |   |
      |
      |
=========

Guess a letter: y
_ y _ _ _ _

  +---+
  |   |
  O   |
  |   |
      |
      |
=========

Guess a letter: u
_ y _ _ _ _
You guessed u, that's not in the word. You lose a life.

  +---+
  |   |
  O   |
 /|   |
      |
      |
=========
Guess a letter: w
_ y _ _ _ _
You guessed w, that's not in the word. You lose a life.

  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========

Guess a letter: v
_ y _ _ _ _
You guessed v, that's not in the word. You lose a life.

  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========

Guess a letter: p
p y _ _ _ _

  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========

Guess a letter: t
p y t _ _ _

  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========

Guess a letter: a
p y t _ _ _
You guessed a, that's not in the word. You lose a life.
Game Over...You Lose!

  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========

HOW TO MAKE A HANGMAN GAME IN PYTHON WITH GRAPHICS?

Yes, we can develop complete graphic software or GUI software using python. To make a hangman game with python graphics, we will use the python Tkinter framework, one of the most powerful python frameworks to develop any GUI-based software.

HOW TO MAKE A HANGMAN GAME IN PYTHON USING TKINTER?

Follow to below steps to make a hangman game in python using Tkinter. But first, let’s install the Tkinter framework in our workstation using the below command.

How to install python Tkinter?

pip install tk

OR

pip3 install tk

Step 1: First, we will import the required libraries needed for the project.

from tkinter import *
from tkinter import messagebox
from string import ascii_uppercase
import random

Step 2: we will initialize the Tkinter.

window = Tk()

Step 3: Now, we will add the title of our game and the list of words we will provide users to guess.

window.title('Hangman-GUESS CITIES NAME By Pythonscholar.com')
word_list= ["python","tensorflow","hangman"]

Step 4: Here, we declare the variables to use images in our game.

photos = [PhotoImage(file="images/hang0.png"), PhotoImage(file="images/hang1.png"), PhotoImage(file="images/hang2.png"),
PhotoImage(file="images/hang3.png"), PhotoImage(file="images/hang4.png"), PhotoImage(file="images/hang5.png"),
PhotoImage(file="images/hang6.png"), PhotoImage(file="images/hang7.png"), PhotoImage(file="images/hang8.png"),
PhotoImage(file="images/hang9.png"), PhotoImage(file="images/hang10.png"), PhotoImage(file="images/hang11.png")]

This is the list of images we will use in the later code.

Note: All the images all available in our github repository.

Step 5: We will define a function to start the new game.

def newGame():
    global the_word_withSpaces
    global numberOfGuesses
    numberOfGuesses =0
   
    the_word=random.choice(word_list)
    the_word_withSpaces = " ".join(the_word)
    lblWord.set(' '.join("_"*len(the_word)))

Step 6: Here will define one another function that will be the core of the game; All the word guessing will be performed here.

def guess(letter):
	global numberOfGuesses
	if numberOfGuesses<11:	
		txt = list(the_word_withSpaces)
		guessed = list(lblWord.get())
		if the_word_withSpaces.count(letter)>0:
			for c in range(len(txt)):
				if txt[c]==letter:
					guessed[c]=letter
				lblWord.set("".join(guessed))
				if lblWord.get()==the_word_withSpaces:
					messagebox.showinfo("Hangman","You guessed it!")
		else:
			numberOfGuesses += 1
			imgLabel.config(image=photos[numberOfGuesses])
			if numberOfGuesses==11:
					messagebox.showwarning("Hangman","Game Over")

Step 7: Now, we will design a simple GUI interface for our python graphic project.

imgLabel=Label(window)
imgLabel.grid(row=0, column=0, columnspan=3, padx=10, pady=40)

lblWord = StringVar()
Label(window, textvariable  =lblWord,font=('consolas 24 bold')).grid(row=0, column=3 ,columnspan=6,padx=10)

n=0

Step 8: Now, we will run a for loop to get all the ascii characters  to print inside the buttons as a keyboard.

for c in ascii_uppercase:
    Button(window, text=c, command=lambda c=c: guess(c), font=('Helvetica 18'), width=4).grid(row=1+n//9,column=n%9)
    n+=1

Button(window, text="New\nGame", command=lambda:newGame(), font=("Helvetica 10 bold")).grid(row=3, column=8)

Step 9: This is the last step in which we will use all the defined functions to execute the code, and last we will call the Tkinter main loop.

newGame()
window.mainloop()

Let’s execute the project now.

Below is the screenshot of our hangman game.

Python Hangman GUI Output 1

The final screenshot will look like the one below.

Python Hangman GUI Output 2

So, our Python Hangman GUI game is completed, and the results are excellent. Here you guys can add more words to the target list to make this game more interesting, or you can play with TKinter to make the interface more attractive.

You can access all the code for the hangman game in python from our github repository also all the images.

Conclusion

Building a python hangman game is elementary, as we saw above with python and its powerful libraries. Here we have used only essential python functions to make a dynamic python game. We have used the Tkinter framework for the advanced version to create a graphical version of the hangman game in python.

Download Project Source Code from GitHub

FAQs

What is Hangman project Python?

The hangman project is a simple multiplayer game developed using python programming as a beginner’s Python project.

How do you make a hangman game in Python?

Hangman game in python can be made using basic python functions like if condition, input/output function, and for loops together.

How do you make a simple game in Python?

Simple games in python can be made using Tkinter, pygame, or just python. A game like Hangman, mad libs generator, or dice roller can be made using python.

Can I build a game with Python?

Yes, you can build basic to advance games in python using many different types of python libraries.

Is Tkinter good for making games?

No Tkinter can be used for making games, but Tkinter is not so good for just game development. Better alternatives like Pygame are good options for making games in python.