Table of contents
1.
Introduction
2.
What is Python?
3.
What is Tkinter?
4.
Prerequisites
5.
Explanation of the Code
5.1.
Importing modules in Python: random and tkinter
5.2.
Defining a Dictionary of Word Lists
5.3.
Function to Choose a Word from the List
5.4.
Class for the Game
5.5.
Function to Update the Display Word when a Letter is Guessed Correctly
5.6.
Function to Handle a Letter Guess
5.7.
Function to create the GUI
5.8.
Function to disable all letter buttons
5.9.
Function to update the hangman image when a letter is guessed incorrectly
5.10.
Function to change the category of words in the Hangman game
5.11.
Function to start the game loop and restart the game
5.12.
Starting the Hangman game
6.
Frequently Asked Questions
6.1.
What is object-oriented programming and how can it be applied in Python?
6.2.
How can I debug my Python code when errors occur?
6.3.
What is a pip and how can it be used in Python?
6.4.
How can I improve the performance of my Python code?
7.
Conclusion
Last Updated: Aug 22, 2025
Medium

Hangman Game in Python

Introduction

Hangman Game using Python and Tkinter

Introducing the Hangman Game in Python using the tkinter module!
Hangman is a classic game that involves guessing letters of a hidden word one by one until you either solve the puzzle or run out of guesses.

In this blog post, we'll explore how to create a simple Hangman game using Python and the tkinter module - which allows us to create a graphical user interface (GUI) for our game. 

We'll cover everything from importing modules, defining functions and classes, and creating a GUI that interacts with the user to play the game. 

What is Python?

Python is a high-level programming language known for its simple syntax, readability, and versatility. It is widely used in various fields, such as web development, data analysis, machine learning, and scientific computing, to name a few.

What is Tkinter?

Tkinter is a Python library that provides a set of tools for creating graphical user interfaces (GUIs) for desktop applications. It is one of the most commonly used GUI libraries for Python and is included with most Python installations. With Tkinter, you can create windows, buttons, labels, menus, and other graphical elements to build a GUI for your Python application.

Prerequisites

To follow this tutorial, you should have the following:

  • A basic understanding of Python programming and the Tkinter library.
  • Python and Tkinter are installed on your computer. You can download the latest version of Python from the official website or use a package manager like pip.
  • If you're a beginner, we recommend starting with a beginner's tutorial to familiarize yourself with the language.
  • With Python and Tkinter, you can create powerful and user-friendly applications.

Explanation of the Code

Importing modules in Python: random and tkinter

In Python, the import statement is used to bring in external modules or libraries into a program.

The random module provides various functions to deal with random numbers, including generating pseudo-random numbers, shuffling sequences randomly, and choosing a random item from a list. 

The tkinter module, on the other hand, provides a way to create GUI (Graphical User Interface) applications in Python.

 It provides a set of standard GUI widgets, such as buttons, labels, textboxes, etc., that can be used to build desktop applications. 

This code creates a window, canvas, labels, buttons, dropdown menus, etc., to build a Hangman game that interacts with the user through the GUI.

import random
import tkinter as tk
You can also try this code with Online Python Compiler
Run Code

Defining a Dictionary of Word Lists

In this code, we see the definition of a dictionary named word_lists. A dictionary is a collection of key-value pairs where each key is associated with a particular value.

The word_lists dictionary has two keys: "fruits" and "coding". 

The values associated with these keys are lists of words related to those categories. 

For example, the "fruits" list contains words such as "apple", "banana", "orange", "kiwi", and "pineapple"

The "coding" list contains words such as "python", "java", "javascript", "php", "ruby", "html", and "css".

This dictionary is used in the choose_word() function to select a word from one of these lists randomly. If no category is specified when calling the function, it chooses a random category first and then selects a word from that category's list.

word_lists = {
  "fruits": ["apple", "banana", "orange", "kiwi", "pineapple"],
  "coding": ["python", "java", "javascript", "php", "ruby", "html", "css"],
}
You can also try this code with Online Python Compiler
Run Code

Function to Choose a Word from the List

This code defines a Python function called choose_word that selects a random word from a list of words. The function takes one argument, category, which is set to None by default.

illustrative image

If a category is not passed as an argument, the function chooses a random category from a dictionary of word lists defined elsewhere in the code.

If a category is passed as an argument, the function selects a word from the corresponding list.

# Function to choose a word from the list
def choose_word(category=None):
  if category is None:
      # Choose a random category and word
      category = random.choice(list(word_lists.keys()))
  word_list = word_lists[category]
  return random.choice(word_list)
You can also try this code with Online Python Compiler
Run Code

After selecting the word list based on the chosen category or a random selection, the function uses a Python random module to pick a random element (word) from the list. It returns that word as the output of the function.

Class for the Game

This code defines a Python class called HangmanGame that represents a game of hangman. The class constructor takes one argument, word, which is the word that the player will try to guess.

The class has the following instance variables:

  • word: the word to be guessed (converted to uppercase)
  • guesses_left: the number of guesses the player has left (set to 6 initially)
  • letters_guessed: a list of letters that the player has already guessed
  • display_word: a string that represents the word with blanks for unguessed letters and actual letters for correctly guessed ones.
# Class for the game
class HangmanGame:
  def __init__(self, word):
      self.word = word.upper()
      self.guesses_left = 6
      self.letters_guessed = []
      # Choose a random index to fill in the guess
      guess_index = random.randint(0, len(self.word) - 1)
      self.display_word = "-" * len(self.word)
      self.display_word = self.display_word[:guess_index] + self.word[guess_index] + self.display_word[guess_index+1:]
      
      self.create_gui()
You can also try this code with Online Python Compiler
Run Code

In addition, the constructor chooses a random index in the word string and replaces the corresponding character in display_word with the actual letter. This is done to give the player a hint about what the word might be.

Finally, the constructor calls a method create_gui which creates the graphical user interface (GUI) for the game. This GUI allows the player to interact with the game by guessing letters and seeing their progress toward solving the puzzle.

Function to Update the Display Word when a Letter is Guessed Correctly

This code defines a Python function called update_display_word that updates the display_word instance variable of the HangmanGame class based on the most recent letter guessed by the player.

# Function to update the display word when a letter is guessed correctly
  def update_display_word(self):
      new_display_word = ""
      for i in range(len(self.word)):
          if self.word[i] == self.display_word[i]:
              new_display_word += self.word[i]
          elif self.word[i] in self.letters_guessed:
              new_display_word += self.word[i]
          else:
              new_display_word += "-"
      self.display_word = new_display_word
      self.word_label.config(text=self.display_word)
You can also try this code with Online Python Compiler
Run Code

The function iterates over each character in the word string and checks if it matches the corresponding character in the display_word. If so, the actual letter is added to the new_display_word

If not, we check whether the letter was already guessed by checking whether it appears in the letters_guessed list. If it has been guessed, the actual letter is added to the new_display_word. Otherwise, the letter is replaced with a dash ("-").

After creating the new_display_word, we update the display_word instance variable with the new value and update the displayed text in the GUI via the word_label.config() method call, which changes the text of a label widget with the updated display_word.

Function to Handle a Letter Guess

This code defines a Python function called guess_letter that handles the player's guess of a letter in the hangman game. The function takes one argument, a letter, which is the letter that the player has guessed.

The function first checks if the letter has already been guessed by the player. The info_label is updated with an appropriate message via the config() method call if it has.

If the letter has not already been guessed, we add the letter to the letters_guessed list and check if the letter is in the target word using a membership operator. If so, we update the display_word by calling the update_display_word() method.

# Function to handle a letter guess
  def guess_letter(self, letter):
      if letter in self.letters_guessed:
          self.info_label.config(text="You already guessed that letter!")
      else:
          self.letters_guessed.append(letter)
          if letter in self.word:
              self.update_display_word()
              if "-" not in self.display_word:
                  self.info_label.config(text="Congratulations, you won!")
                  self.disable_buttons()
          else:
              self.guesses_left -= 1
              self.info_label.config(text="Sorry, wrong letter!")
              self.update_hangman()
              if self.guesses_left == 0:
                  self.info_label.config(text="Sorry, you lost! The word was {}".format(self.word))
                  self.disable_buttons()
You can also try this code with Online Python Compiler
Run Code

If all letters have been revealed (i.e., no "-"s left in the display_word), we update the info_label to display a message congratulating the player on winning and disabling any further input.

If the guessed letter is not in the word, we decrement the number of remaining guesses guesses_left, update the info_label, and update the display of the hangman image (via the update_hangman() method call).

If the number of remaining guesses_left becomes zero, indicating that the player has used up all their guesses, we update the info_label to show a message informing the player that they lost and displaying the correct answer. Finally, the disable_buttons() method is called to prevent any further input.

Function to create the GUI

The create_gui function is responsible for creating a Hangman game's graphical user interface (GUI). Here's what it does:

# Function to create the GUI
  def create_gui(self):
      self.root = tk.Tk()
      self.root.title("Hangman")
      
      # Create a dropdown menu for selecting category
      self.category_var = tk.StringVar()
      self.category_var.set("Select category")
      categories = ["All"] + list(word_lists.keys())
      self.category_menu = tk.OptionMenu(self.root, self.category_var, *categories, command=self.change_category)
      self.category_menu.grid(row=0, column=0, columnspan=2)

      self.canvas = tk.Canvas(self.root, width=200, height=250)
      self.canvas.grid(row=1, column=0, columnspan=2)
      self.images = [
          tk.PhotoImage(file="hangman/hangman0.png"),
          tk.PhotoImage(file="hangman/hangman1.png"),
          tk.PhotoImage(file="hangman/hangman2.png"),
          tk.PhotoImage(file="hangman/hangman3.png"),
          tk.PhotoImage(file="hangman/hangman4.png"),
          tk.PhotoImage(file="hangman/hangman5.png"),
          tk.PhotoImage(file="hangman/hangman6.png"),
      ]
      self.hangman_image = self.canvas.create_image(100, 110, image=self.images[0])

      self.word_label = tk.Label(self.root, text=self.display_word, font=("Arial", 24))
      self.word_label.grid(row=2, column=0, columnspan=2)

      self.info_label = tk.Label(self.root, text="Guess a letter!", font=("Arial", 16))
      self.info_label.grid(row=3, column=0, columnspan=2)

      self.button_frame = tk.Frame(self.root)
      self.button_frame.grid(row=4, column=0, columnspan=2)
      
      self.restart_button = tk.Button(self.root, text="Restart", command=self.restart_game, bg="green", fg="white", font=("Arial", 16), relief="ridge")
      self.restart_button.grid(row=5, column=0, columnspan=2)


      for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
          # Generate random colors for each button
          bg_color = '#' + ''.join(random.choices('0123456789ABCDEF', k=6))
          fg_color = 'white' if int(bg_color[1:], 16) > 0xffffff/2 else 'black'
          
          # Create the button with the random colors
          button = tk.Button(self.button_frame, text=letter, width=3, bg=bg_color, fg=fg_color, command=lambda l=letter: self.guess_letter(l))
          button.pack(side="left")
You can also try this code with Online Python Compiler
Run Code
  • It creates a root window using the tk.Tk() method, which serves as the main window of the GUI.
  • It sets the title of the root window to "Hangman".
  • It creates a dropdown menu using the OptionMenu widget from tkinter. The menu displays a list of categories to choose from and allows the player to select one.
  • It creates a canvas using the Canvas widget from tkinter. The canvas is used to display the hangman image.
  • It loads a list of images using the PhotoImage method from tkinter.
  • It creates a label displaying the hidden word the player needs to guess.
illustrative image
  • It creates a label to display hints and game information to the player.
  • It creates a frame to hold the letter buttons.
  • It creates a button to restart the game.
  • It creates 26 letter buttons, one for each letter of the alphabet. Each button has a unique background color and foreground color generated using random hexadecimal codes. When clicked, they call the guess_letter function to handle the guess.

Function to disable all letter buttons

The disable_buttons function is a helper function used in the Hangman game. 

  # Function to disable all letter buttons
  def disable_buttons(self):
      for widget in self.button_frame.winfo_children():
          widget.config(state="disabled")
You can also try this code with Online Python Compiler
Run Code

Here's what it does:

  • It uses a for loop to iterate through each button widget that is a child of the button_frame.
  • For each button, it sets the state of the button to "disabled" using the config method with the state parameter.
  • A disabled button cannot be clicked and its appearance changes to indicate to the player that it is no longer functional. This function is called when the game ends so that the player cannot continue guessing letters after the game has already been won or lost.

Function to update the hangman image when a letter is guessed incorrectly

The update_hangman function is used in the Hangman game to update the graphical representation of the hangman as the player makes incorrect guesses. 

# Function to update the hangman image when a letter is guessed incorrectly
  def update_hangman(self):
      self.canvas.itemconfig(self.hangman_image, image=self.images[6-self.guesses_left])
You can also try this code with Online Python Compiler
Run Code

Here's what it does:

  • It updates the image displayed on the canvas by changing the configuration of the hangman_image item using the itemconfig method.
  • The new image is selected from the list of images loaded in the self.images list. The index of the image corresponds to the number of remaining guesses. Since the hangman has 7 parts, the index is calculated as 6-self.guesses_left.
  • This function is called each time the player makes an incorrect guess to update the visual representation of the hangman and show the player how many guesses they have left before losing the game.

Function to change the category of words in the Hangman game

The change_category function is used in the Hangman game to update the category of words displayed by the game when the player selects a new category from the dropdown menu. 

  def change_category(self, category):
      word = choose_word(None if category == "All" else category)
      self.root.destroy()
      game = HangmanGame(word)
      game.start_game()
You can also try this code with Online Python Compiler
Run Code

Here's what it does:

  • It takes a parameter category, which represents the newly selected category.
  • It calls the choose_word function to select a new word from the word list based on the selected category. If the "All" category is selected, the function returns a word from any category at random.
  • It destroys the current root window using the destroy method so that a new game can start with the updated word and category.
  • It creates a new instance of the HangmanGame class using the selected word as a parameter.
  • It calls the start_game method of the new HangmanGame object to start the game with the updated word and category. This function is called whenever the player selects a new category to play with, allowing the player to play with different sets of words each time.

Function to start the game loop and restart the game

The start_game function is used in the Hangman game to start the main event loop of the GUI, thereby starting the game. 

Here's what it does:

  • It calls the mainloop method of the root window to start the game loop.

The restart_game function is also used in the Hangman game to restart the game when the player clicks on the "Restart" button. Here's what it does:

  # Function to start the game loop
  def start_game(self):
      self.root.mainloop()

  def restart_game(self):
      self.root.destroy()
      word = choose_word()
      self.__init__(word)
      self.start_game()
You can also try this code with Online Python Compiler
Run Code
  • It destroys the current root window using the destroy method so that a new game can start with a new word.
  • It selects a new word at random from the word list using the choose_word function.
  • It initializes a new instance of the HangmanGame class using the selected word as a parameter. This allows for a completely new game to start with a new hidden word, category, and guesses left.
  • It calls start_game to initiate the main event loop for the new HangmanGame object.

These functions are called whenever the player starts or restart the game, allowing the player to play multiple times without having to quit and restart the program.

Starting the Hangman game

This code block starts an instance of the Hangman game. 

# Start the game by choosing a word and creating a HangmanGame object
word = choose_word()
game = HangmanGame(word)
game.start_game()
You can also try this code with Online Python Compiler
Run Code

Here's what it does:

  • It selects a random word from the word list using the choose_word function.
  • It creates an instance of the HangmanGame class using the chosen word as a parameter.
  • It calls the start_game method of the HangmanGame object to initiate the main event loop for the game, thereby starting the game
illustrative image

This code is called when the program first runs and is the entry point into the Hangman game, allowing the player to start a new game with a random hidden word.

Practice this code with the help of Online Python Compiler

Frequently Asked Questions

What is object-oriented programming and how can it be applied in Python?

Object-oriented programming is a programming paradigm that focuses on creating objects and classes with specific attributes and behaviors, which can then be used to build larger programs. In Python, you can create objects using classes and define their properties and methods.

How can I debug my Python code when errors occur?

There are several ways to debug Python code when errors occur, including using print statements, using the Python Debugger (pdb), and using Integrated Development Environments (IDEs) such as PyCharm or VSCode.

What is a pip and how can it be used in Python?

Pip is a package manager for Python that allows you to install and manage third-party packages and libraries. It can be used by running commands in the command line or terminal, such as 'pip install [package_name]'.

How can I improve the performance of my Python code?

To improve the performance of Python code, you can use various techniques such as optimizing loops and data structures, using list and dictionary comprehensions, and avoiding unnecessary function calls. Additionally, you can use profiling tools such as cProfile to identify areas of your code that may be causing performance issues.

Conclusion

In conclusion, the code above demonstrates how to write a Hangman Game using Python and Tkinter. 

The program uses word lists to randomly select a word for the user to guess, while also allowing the user to select specific categories. 

Through this program, users can improve their programming skills by learning how to use various functions like random.choice() and Tkinter's widgets such as OptionMenu(), Canvas(), and Button().

Recommended Readings:

Live masterclass