I'm trying to make a little pop-up interface before my game to choose difficulties. The problem I'm having is that after I click yes on the first messagebox.askyesno()
the whole pop up disappears and I have no idea on how to know which button was pressed to return an output. This is my first time using tkinter and messagebox so any help is greatly appreciated.
This is my code:
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()
What about an else
statement ;-)? Consider what your code is doing: if you click 'Yes', it creates some Button on a main window that you have withdrawn. Then, immediately after you deiconify it, you destroy it. Reshuffle your code like follows:
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()
Note that you can also assign the outcome of messagebox.askyesno
to a variable:
answer = messagebox.askyesno("Welcome to Snake!", "Would you like to play?")