pythontkinter

How can I stop my tkinter hangman game accepting a correct letter more than once?


I am making a python hangman game using tkinter. However, after guessing a correct letter, it continues to accept that letter but marking it as wrong. This is my guess function:

def guess_letter(self, event=None):
    guess = self.entry.get().lower()
    self.entry.delete(0, tk.END)

    if not guess or len(guess) != 1 or not guess.isalpha()
        return

    self.guessed_letters.add(guess)
    self.guessed_label.config(text="Guessed Letters: " + ", ".join(sorted(self.guessed_letters)))

    if guess in self.word:
        for i, letter in enumerate(self.word):
            if letter == guess:
                self.display_word[i] = guess
        self.word_label.config(text=" ".join(self.display_word))
    else:
        self.tries_left -= 1
        self.draw_hangman()

    if "_" not in self.display_word:
        messagebox.showinfo("Hangman", "You won!")
        self.master.quit()
    elif self.tries_left == 0:
        messagebox.showinfo("Hangman", f"You lost! The word was: {''.join(self.word)}")
        self.master.quit()

I want it only to register guesses as wrong if they have not been guessed before. What is a method I could use to make it not accept an already guessed letter without any repercussions?


Solution

  • I have a fix. I have replaced:

            if not guess or len(guess) != 1 or not guess.isalpha():
                return
    

    With:

            if not guess or len(guess) != 1 or not guess.isalpha() or guess in self.guessed_letters:
                return
    

    This checks if a letter has already been guessed, and doesn't take away lives if it has.