I am trying to build a simple hangman game. I want to have a window at the beginning to ask for the "secret word". I then want that window to close and have another window open with the game. I can't think of a way to do this without building the entire game within a funciton. How is best to accomplish this?
CodePudding user response:
I believe what you are looking for is a Toplevel
window and it behaves just like a normal root window. Below is a quick and dirty example:
import tkinter as tk
root = tk.Tk()
root.title("Game window")
root.iconify()#Hide from user site, still exists as a minimised window
def submitSecretWord():
#code to collect secret word or what ever
root.deiconify()#Make visible
second_window.destroy()#close second window
#make toplevel window
second_window = tk.Toplevel(master=root)
#make widgets
secret_word_entry = tk.Entry(master=second_window)#Belongs to the second window
submit_button = tk.Button(master=second_window, text="Submit secret word", command=submitSecretWord) #Belongs to the second window
#pack widgets
secret_word_entry.pack(side=tk.LEFT)
submit_button.pack(side=tk.RIGHT)
root.mainloop()
CodePudding user response:
Create another window? Try this:
use multiple functions
from tkinter import *
from turtle import onclick
def gameWindow(word):
window = Tk()
Label(text=word).pack()
# your game code
def anotherGuess():
window.destroy()
getWord()
Button(text='another guess?', command=anotherGuess).pack()
window.mainloop()
def getWord():
window = Tk()
entry = Entry(master=window)
entry.pack()
def onclick():
word = entry.get()
window.destroy()
gameWindow(word)
btn = Button(master=window, text="submit", command=onclick)
btn.pack()
window.mainloop()
def main():
getWord()
if __name__ == '__main__':
main()