防止打开多个顶层?

时间:2015-08-07 06:06:07

标签: python python-3.x tkinter

我有一个面向对象的tkinter程序设置。 我已初始化一个变量以将Toplevel()存储为

self.toplevel = None

然后,当我创建实际的Toplevel窗口时,我只需将其分配给变量:

self.toplevel = Toplevel()

事情是......当Toplevel()窗口关闭时,值仍然保留在变量self.toplevel中。关闭窗口后如何将变量重置为无,以便我可以执行检查:

if (self.toplevel == None):
    self.toplevel = Toplevel()

还是有其他方法可以阻止多个Toplevel Windows打开吗?

2 个答案:

答案 0 :(得分:2)

选中此How do I handle the window close event in Tkinter?

None关闭使用回调函数self.toplevel后,将值Toplevel分配给TopCloses。为此,在GUI类中编写一个方法来访问toplevel属性,并将其值设置为回调函数内的None

在您的主程序中,

def TopCloses():
    top.destroy()
    #Call the setTopLevel method and assign the attribute toplevel value None
    guiObject.setTopLevel(None)

top.protocol("WM_DELETE_WINDOW", TopCloses)
root.mainloop()

答案 1 :(得分:1)

这是我的解决方案:

#somewhere in __init__ make
self.window = None
#I took this piece of code from my bigger app and I have a function 
#self.makevariables(), which is called in init, which contains the line above.
def instructions(self):      
    if self.window == None: #here I check whether it exists, if not make it, else give focus to ok button which can close it
        self.window = Toplevel(takefocus = True)
        #some optional options lol
        self.window.geometry("200x200")
        self.window.resizable(0, 0)
        #widgets in the toplevel
        Label(self.window, text = "NOPE").pack() 
        self.window.protocol("WM_DELETE_WINDOW", self.windowclosed) #this overrides the default behavior when you press the X in windows and calls a function
        self.okbutton = Button(self.window, text = "Ok", command = self.windowclosed, padx = 25, pady = 5)
        self.okbutton.pack()
        self.okbutton.focus()
        self.okbutton.bind("<Return>", lambda event = None:self.windowclosed())
    else:
        self.okbutton.focus()  #You dont need to give focus to a widget in the TopLevel, you can give the focus to the TopLevel, depending how you want it
       #self.window.focus() works too    
def windowclosed(self): #function to call when TopLevel is removed
    self.window.destroy()
    self.window = None