Python Hangman Game with GUI Project: Tkinter vs PyQt5
Hangman Game with GUI:
Enhance the Hangman game by adding a graphical user interface.
From Wikipedia - Hangman is a guessing game for two or more players. One player thinks of a word, phrase, or sentence and the other(s) try to guess it by suggesting letters or numbers within a certain number of guesses. Originally a paper-and-pencil game, now it's available in an electronic version.
The program updates the visual representation of the Hangman game based on the user's input. It provides feedback on the guess letters and game state.
Input values:
User interacts with the "graphical user interface" by clicking buttons to select letters for guessing.
Output value:
Visual representation of the Hangman game with feedback on guessed letters and game state.
Example:
Input values: User clicks the button 'A' to guess the letter 'A'. Output value: Visual representation updates to show the letter 'A' in the word if it exists, or displays the hangman figure if the letter is incorrect. Input values: User clicks the button 'B' to guess the letter 'B'. Output value: Visual representation updates to show the letter 'B' or displays the hangman figure if the letter is incorrect. Input values: User clicks the button 'T' to guess the letter 'T'. Output value: Visual representation updates to show the letter 'T' in the word if it exists, or displays the hangman figure if the letter is incorrect. Input values: User clicks the button 'E' to guess the letter 'E'. Output value: Visual representation updates to show the letter 'E' in the word if it exists, or displays the hangman figure if the letter is incorrect. Input values: User clicks the button 'S' to guess the letter 'S'. Output value: Visual representation updates to show the letter 'S' in the word if it exists, or displays the hangman figure if the letter is incorrect. Input values: User clicks the button 'Y' to guess the letter 'Y'. Output value: Visual representation updates to show the letter 'Y' in the word if it exists, or displays the hangman figure if the letter is incorrect. Input values: User clicks the button 'N' to guess the letter 'N'. Output value: Visual representation updates to show the letter 'N' in the word if it exists, or displays the hangman figure if the letter is incorrect.
Here are two different solutions for a "Hangman Game with GUI" in Python. Each solution uses a different GUI framework to create an interactive Hangman game, allowing users to guess letters and providing visual feedback based on their guesses.
Solution 1: Using Tkinter
This solution uses Tkinter, a standard Python library for creating graphical user interfaces.
Code:
# Solution 1: Hangman Game with GUI Using Tkinter
import tkinter as tk
from tkinter import messagebox
import random
class HangmanGame:
"""Class to create a Hangman game using Tkinter."""
def __init__(self, master):
"""Initialize the Hangman game with the main Tkinter window."""
self.master = master
self.master.title("Hangman Game")
self.word_list = ["python", "hangman", "programming", "developer", "algorithm"]
self.word_to_guess = random.choice(self.word_list)
self.guessed_letters = set()
self.remaining_attempts = 6
# Create and display labels and buttons
self.word_display = tk.StringVar()
self.update_word_display()
tk.Label(master, textvariable=self.word_display, font=("Arial", 20)).pack(pady=10)
self.buttons_frame = tk.Frame(master)
self.buttons_frame.pack()
# Create letter buttons
for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
button = tk.Button(self.buttons_frame, text=letter, width=4, command=lambda l=letter: self.guess_letter(l))
button.grid(row=ord(letter) // 10, column=ord(letter) % 10)
def update_word_display(self):
"""Update the displayed word based on the guessed letters."""
display = ''.join([letter if letter in self.guessed_letters else '_' for letter in self.word_to_guess])
self.word_display.set(' '.join(display))
def guess_letter(self, letter):
"""Handle a letter guess by the user."""
letter = letter.lower()
if letter in self.guessed_letters:
messagebox.showinfo("Hangman", f"You've already guessed '{letter.upper()}'.")
return
self.guessed_letters.add(letter)
if letter in self.word_to_guess:
self.update_word_display()
if set(self.word_to_guess) <= self.guessed_letters:
messagebox.showinfo("Hangman", "Congratulations! You've won!")
self.master.quit()
else:
self.remaining_attempts -= 1
if self.remaining_attempts == 0:
messagebox.showinfo("Hangman", f"Game over! The word was '{self.word_to_guess}'.")
self.master.quit()
else:
messagebox.showinfo("Hangman", f"Incorrect! {self.remaining_attempts} attempts left.")
# Run the Tkinter Hangman game
root = tk.Tk()
game = HangmanGame(root)
root.mainloop()
Output:
Explanation:
- HangmanGame Class:
- __init__() Constructor: Initializes the game, sets up the Tkinter window, selects a random word, and creates buttons for each letter.
- update_word_display() Method: Updates the display of the word with guessed letters.
- guess_letter(letter) Method: Handles the user's letter guess, checks if the letter is in the word, updates the game state, and displays messages for winning or losing.
- Creating Buttons for Letters:
- The buttons for each letter are created dynamically using a loop and added to the Tkinter frame.
- Message Boxes:
- messagebox.showinfo() is used to display messages for incorrect guesses, already guessed letters, and the game result.
Solution 2: Using PyQt5
This solution uses PyQt5, a popular Python library for creating cross-platform desktop applications with a GUI.
Code:
# Solution 2: Hangman Game with GUI Using PyQt5 (Updated with Horizontal Button Layout)
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget, QMessageBox, QGridLayout
import random
class HangmanGame(QMainWindow):
"""Class to create a Hangman game using PyQt5."""
def __init__(self):
"""Initialize the Hangman game with the main PyQt5 window."""
super().__init__()
self.setWindowTitle("Hangman Game")
self.setGeometry(100, 100, 400, 300)
self.word_list = ["python", "hangman", "programming", "developer", "algorithm"]
self.word_to_guess = random.choice(self.word_list)
self.guessed_letters = set()
self.remaining_attempts = 6
# Set up the user interface
self.setup_ui()
def setup_ui(self):
"""Set up the user interface with labels and buttons."""
main_widget = QWidget()
self.setCentralWidget(main_widget)
main_layout = QVBoxLayout() # Main vertical layout
# Display the current state of the word
self.word_display = QLabel()
self.update_word_display()
main_layout.addWidget(self.word_display)
# Create a grid layout for letter buttons
button_layout = QGridLayout()
# Create letter buttons and add them to the grid layout
for index, letter in enumerate('ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
button = QPushButton(letter)
button.clicked.connect(lambda _, l=letter: self.guess_letter(l))
button_layout.addWidget(button, index // 9, index % 9) # Arrange buttons in a grid (3 rows x 9 columns)
# Add the button grid layout to the main layout
main_layout.addLayout(button_layout)
main_widget.setLayout(main_layout)
def update_word_display(self):
"""Update the displayed word based on the guessed letters."""
display = ' '.join([letter if letter in self.guessed_letters else '_' for letter in self.word_to_guess])
self.word_display.setText(display)
def guess_letter(self, letter):
"""Handle a letter guess by the user."""
letter = letter.lower()
if letter in self.guessed_letters:
QMessageBox.information(self, "Hangman", f"You've already guessed '{letter.upper()}'.")
return
self.guessed_letters.add(letter)
if letter in self.word_to_guess:
self.update_word_display()
if set(self.word_to_guess) <= self.guessed_letters:
QMessageBox.information(self, "Hangman", "Congratulations! You've won!")
self.close()
else:
self.remaining_attempts -= 1
if self.remaining_attempts == 0:
QMessageBox.information(self, "Hangman", f"Game over! The word was '{self.word_to_guess}'.")
self.close()
else:
QMessageBox.information(self, "Hangman", f"Incorrect! {self.remaining_attempts} attempts left.")
# Run the PyQt5 Hangman game
app = QApplication([])
window = HangmanGame()
window.show()
app.exec_()
Output:
Explanation:
- QGridLayout for Button Layout:
- A QGridLayout is used to organize the letter buttons in a grid format.
- button_layout.addWidget(button, index // 9, index % 9):
- Arranges buttons in 3 rows with 9 buttons per row (i.e., 3x9 grid).
- index // 9 determines the row number.
- index % 9 determines the column number.
- Main Vertical Layout (QVBoxLayout):
- The main layout (main_layout) is a QVBoxLayout that first adds the QLabel for the word display.
- Then, it adds the QGridLayout (button_layout) for the letter buttons, aligning them horizontally.
- Interactive Buttons:
- Each button is connected to the guess_letter function to handle the user's input.
- This layout ensures that the buttons are neatly aligned horizontally and organized in rows.
- Solution 1: Using Tkinter:
- Uses Tkinter, a standard Python library that is easy to learn and set up.
- Suitable for simple GUI applications and quick prototypes.
- Limited styling and customization options compared to PyQt5.
- Solution 2: Using PyQt5:
- Uses PyQt5, a more powerful library for creating cross-platform desktop applications.
- Provides more advanced features and customization options.
- Suitable for more complex and scalable GUI applications.
Differences Between the Two Solutions:
Both solutions effectively implement a Hangman game with a graphical user interface, providing interactive gameplay with feedback on guessed letters and the game state.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/projects/python/python-hangman-game-with-gui-project.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics