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

Discussão em 'Python' iniciado por Stack, Abril 29, 2025.

  1. Stack

    Stack Membro Participativo

    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 = 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?

    Continue reading...

Compartilhe esta Página