You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter窗口销毁错误及Hangman游戏GUI重启/退出功能实现问题

Hey there! Let's fix up your Hangman GUI to add that restart/exit window feature you need. I’ve adjusted your core code to include the new functionality, and here’s how it works:

Solution Code
from Tkinter import *

def start_hangman():
    global root, item, oldString, guess_entry, result_label

    # Clean up any existing main window
    try:
        root.destroy()
    except NameError:
        pass

    # Initialize game variables
    item = "BOO"
    oldString = "-" * len(item)

    # Create main game window
    root = Tk()
    root.title("Hangman Game")

    # Display current guess progress
    result_label = Label(root, text=oldString, font=('Arial', 24))
    result_label.pack(pady=20)

    # Guess input area
    guess_entry = Entry(root, font=('Arial', 18))
    guess_entry.pack(pady=10)

    submit_btn = Button(root, text="Submit Guess", command=check_guess)
    submit_btn.pack(pady=10)

    root.mainloop()

def check_guess():
    global oldString
    guess = guess_entry.get().upper()
    guess_entry.delete(0, END)

    # Validate input (single letter only)
    if len(guess) != 1 or not guess.isalpha():
        result_label.config(text="Please enter a single letter!")
        return

    # Update the guess string
    new_string = list(oldString)
    correct_guess = False
    for i in range(len(item)):
        if item[i] == guess:
            new_string[i] = guess
            correct_guess = True
    oldString = ''.join(new_string)
    result_label.config(text=oldString)

    # Check if game is won (you can add a losing condition too!)
    if oldString == item:
        result_label.config(text=f"Congrats! You won! The word was {item}")
        show_end_window()

def show_end_window():
    # Create the end-of-game popup window
    end_window = Toplevel()
    end_window.title("Game Over")

    Label(end_window, text="What would you like to do next?", font=('Arial', 16)).pack(pady=20)

    # Restart button: Close popup, then restart the game (which closes old main window)
    restart_btn = Button(end_window, text="Restart Game", font=('Arial', 14), 
                         command=lambda: [end_window.destroy(), start_hangman()])
    restart_btn.pack(side=LEFT, padx=20, pady=10)

    # Exit button: Close both main window and popup to quit
    quit_btn = Button(end_window, text="No, Exit", font=('Arial', 14), 
                      command=lambda: [root.destroy(), end_window.destroy()])
    quit_btn.pack(side=RIGHT, padx=20, pady=10)

    # Lock main window until popup is closed
    root.wait_window(end_window)

# Start the game when the script runs
if __name__ == "__main__":
    start_hangman()
Key Details to Note
  • Game Initialization in a Function: I wrapped the core game setup into start_hangman() so we can easily restart it. This function destroys any existing main window before creating a new one, so there’s no clutter from old windows.
  • End-of-Game Popup: The show_end_window() function creates a Toplevel window (a separate popup) with your two buttons. This keeps the UI clean and focused on the user’s next choice.
  • Button Logic:
    • The Restart Game button uses a lambda to first close the popup, then call start_hangman() to launch a fresh game session.
    • The No, Exit button closes both the main game window and the popup, fully exiting the application.
  • Input Validation: I added a quick check to make sure users only enter single letters—you can expand this later if you want to handle invalid inputs more gracefully.

To test it out, just enter "b" then "o" like you mentioned. Once you guess the full word, the popup will appear, and you can choose to restart or exit!

内容的提问来源于stack exchange,提问作者user9587850

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:53:54