我的按钮在初始弹出后没有出现 - Python 消息框

My button doesn't apear after the initial popup - Python Message Box

我想在我的游戏前做一个小的弹出界面来选择难度。我遇到的问题是,在我点击第一个 messagebox.askyesno() 上的是之后,整个弹出窗口消失了,我不知道如何知道按下哪个按钮以 return 输出。这是我第一次使用 tkintermessagebox 所以非常感谢任何帮助。

这是我的代码:

import tkinter as tk
from tkinter import messagebox

def start_game():
    root = tk.Tk()
    root.attributes("-topmost", True)
    root.withdraw()
    if messagebox.askyesno("Welcome to Snake!", "Would you like to play?") == True:
        mainLabel = tk.Label(root, text='Choose a dificulty:')
        easy_ask = tk.Button(root, text='Easy')
        medium_ask = tk.Button(root, text='Medium')
        hard_ask = tk.Button(root, text='Hard')

        mainLabel.pack(side=tk.LEFT)
        easy_ask.pack(side=tk.LEFT)
        medium_ask.pack(side=tk.LEFT)
        hard_ask.pack(side=tk.LEFT)

    root.deiconify()
    root.destroy()
    root.quit()

    root.mainloop()

start_game()

else 语句怎么样 ;-)?考虑一下您的代码在做什么:如果您单击 'Yes',它会在您撤回的主 window 上创建一些按钮。然后,在你去图标化它之后,立即销毁它。重新整理您的代码,如下所示:

import tkinter as tk
from tkinter import messagebox

def start_game():
    root = tk.Tk()
    root.attributes("-topmost", True)
    root.withdraw()
    if messagebox.askyesno("Welcome to Snake!", "Would you like to play?") == True:
        root.deiconify()                    # <--- deiconify under the True condition
        mainLabel = tk.Label(root, text='Choose a dificulty:')
        easy_ask = tk.Button(root, text='Easy')
        medium_ask = tk.Button(root, text='Medium')
        hard_ask = tk.Button(root, text='Hard')

        mainLabel.pack(side=tk.LEFT)
        easy_ask.pack(side=tk.LEFT)
        medium_ask.pack(side=tk.LEFT)
        hard_ask.pack(side=tk.LEFT)
    else:
        root.destroy()                       # <--- destroy and quit under the False condition
        root.quit()

    root.mainloop()

start_game()

注意您还可以将messagebox.askyesno的结果分配给一个变量:

answer = messagebox.askyesno("Welcome to Snake!", "Would you like to play?")