[英]Closing Tkinter window and opening another
I am trying to build a simple hangman game.我正在尝试构建一个简单的刽子手游戏。 I want to have a window at the beginning to ask for the "secret word".
我想在开头有一个 window 来询问“秘密词”。 I then want that window to close and have another window open with the game.
然后我希望 window 关闭并在游戏中打开另一个 window。 I can't think of a way to do this without building the entire game within a funciton.
如果不在一个函数中构建整个游戏,我想不出一种方法来做到这一点。 How is best to accomplish this?
如何最好地做到这一点?
Create another window?创建另一个 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()
I believe what you are looking for is a Toplevel
window and it behaves just like a normal root window.我相信您正在寻找的是顶级
Toplevel
,它的行为就像普通的根 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.