我今天正在使用Tkinter编写我的第一个GUI程序,我偶然发现了一个问题。我正在尝试制作一款游戏,它从一个介绍窗口开始,在你按下按钮后关闭,然后打开一个新窗口,你可以在其中选择两种模式之一。不幸的是,我就是无法运行它。它看起来有点像这样。
#These are the functions that I defined to make it work
def start():
root.destroy()
def Rules_mode_1():
root.destroy
rules1 = Tk()
understood1 = Button(rules1, text="I understood", command="Start_game_mode_1")
understood.pack()
rules1.mainloop
# I haven't added rules 2 yet cause I couldn't get it to work with rules 1 so I haven't even #bothered but it would be the same code just switching the 1 for a 2. But really it isn't even
#necessary to have 2 different rule functions because the rules are the same but I couldn't think
#of another way to go about it. if you have an idea let me know
def Start_game_mode_1():
rules1.destroy #<----- THIS IS WHERE THE PROBLEM LIES. JUST DOESN'T RUN
gamemode1 = Tk()
#Here I would have the game
gamemode1.mainloop()
#now same here don't have gamemode 2 yet cause it just doesn't work yet
#This is where it really starts
root = Tk()
startbutton = Button(root, text="Start", command=start)
startbutton.pack
root.mainloop
root = Tk()
def mode():
mode1 = Button(root, command=Rules_mode_1)
mode1.pack
mode2 = #Buttonblablabla
mode()
root.mainloop()
现在我已经试了几个小时,试图给主循环取不同的名字。例如,给出
rules1.mainloop
#the name
root.mainloop
但这显然没有奏效。我尝试了几十个辅助函数和lambda表达式,做了几个小时的研究,但似乎无法修复。有人有什么想法吗?请尊重并记住这是我第一次使用Tkinter。
谢谢你的帮助!
在这些评论对我没有真正帮助之后,我只是尝试了几个小时,以防有人遇到类似的问题,并阅读到:rules1
变量在一个函数中,因此只是局部变量,这意味着它不能在另一个函数中将其销毁。我通过将其设置为全局来修复它,比如:
def Rules_mode_1():
root.destroy
global rules1
rules1 = Tk()
understood1 = Button(rules1, text="I understood", command="Start_game_mode_1")
understood.pack()
rules1.mainloop
之后,我可以在下一个函数中破坏主循环。