我正在尝试在
tkinter
中编写一个GUI,将根设置为“暗模式”,等待特定的时间,然后关闭或退出自身,同时应生成一个新的顶级。当我关闭顶层后,撤回的主窗口应该会再次弹出。因此我使用了 if 语句,但我得到了 NameError: newWindow not defined
,即使我将其设置为全局。
这是我的代码:
from tkinter import *
def answer(event):
AnsLabel["text"]="You clicked the Button!"
def darkmode(event):
Hallo["fg"]="white"
Hallo["bg"]="black"
main["bg"]="black"
AnsLabel["bg"]="black"
AnsLabel["fg"]="white"
button["bg"]="black"
button["fg"]="white"
main.after(3000,createWindow)
def createWindow():
global newWindow
newWindow=Toplevel()
newLabel=Label(newWindow,text="You found the secret function!")
newLabel.pack()
main.withdraw()
main=Tk()
Hallo=Label(main,text="Hello")
button=Button(main,text="BUTTON")
button.bind("<Button-1>",answer)
button.bind("<Button-3>",darkmode)
AnsLabel=Label(main,text="Hello!")
Hallo.pack()
button.pack()
AnsLabel.pack()
if not newWindow.winfo_exists():
main.deiconify()
main.mainloop()
仅调用一次createWindow,在主循环启动之前,第一次不会出现这种情况。您尝试在此之前访问 newWindow 。 – 切普纳
我找到了一个解决方案,添加变量
Dark
来检查之前是否调用了createWindow
。尽管如此,它还是没有按预期工作,因为 main.deiconify()
不会再次打开 main
窗口。
def answer(event):
AnsLabel["text"]="You clicked the Button!"
def darkmode(event):
Hallo["fg"]="white"
Hallo["bg"]="black"
main["bg"]="black"
AnsLabel["bg"]="black"
AnsLabel["fg"]="white"
button["bg"]="black"
button["fg"]="white"
global Dark
Dark=True
main.after(3000,createWindow)
def createWindow():
global newWindow
newWindow=Toplevel()
newLabel=Label(newWindow,text="You found the secret function!")
newLabel.pack()
main.withdraw()
Dark=False
main=Tk()
Hallo=Label(main,text="Hello")
button=Button(main,text="BUTTON")
button.bind("<Button-1>",answer)
button.bind("<Button-3>",darkmode)
AnsLabel=Label(main,text="Hello!")
Hallo.pack()
button.pack()
AnsLabel.pack()
if Dark and not newWindow.winfo_exists():
main.deiconify()
main.mainloop()