python 是否阻止打开多个顶级?

eoxn13cs  于 2022-12-28  发布在  Python
关注(0)|答案(3)|浏览(114)

我已经建立了一个面向对象的tkinter程序。我已经初始化了一个变量来存储Toplevel()

self.toplevel = None

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

self.toplevel = Toplevel()

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

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

或者是否有其他方法可以防止打开多个Toplevel窗口?

puruo6ea

puruo6ea1#

检查此How do I handle the window close event in Tkinter?
Toplevel关闭后,使用回调函数TopCloses将值None赋值给self.toplevel。为此,在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()
vcirk6k6

vcirk6k62#

下面是我的解决方案:

#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
yquaqz18

yquaqz183#

这些都是过于复杂的解决方案海事组织。
我只是这样使用win32gui:

toplevel_hwid = win32gui.FindWindow(None, '<Top Level Window Title>')

if toplevel_hwid:
    print(f'Top level window already open with HWID: {toplevel_hwid}')
    win32gui.SetForegroundWindow(toplevel_hwid)
    return
else:
    <create new top level>

简单、方便,让您可以灵活地关闭、移动、聚焦等。

相关问题