如何在tkinter中限制Toplevel窗口的数量

时间:2016-02-25 17:43:32

标签: user-interface python-3.x tkinter toplevel

我有一些代码可以为用户创建一个顶级窗口 按下按钮。

但是我想将顶级窗口的数量限制为一个,因此用户无法对按钮进行垃圾邮件并打开五十个窗口。

import tkinter as tk

class app():

    def __init__(self,master):

        self.master = master    
        master.configure(background = '#002e3d')
        master.title('Test!')
        master.geometry = master.geometry('660x550+200+200')
        master.resizable(width = False,height = False)
        self.button = tk.Button(master,text = 'Test'command = self.searchmenu)
        self.button.pack()

    def searchmenu(self):
        Demo()


class Demo():

    def __init__(self):
        self.top = tk.Toplevel()
        self.top.title('Search!')


def main():

    root = tk.Tk()
    window = app(root)
    root.mainloop()

1 个答案:

答案 0 :(得分:1)

如果您引用了您创建的Demo对象(无论我推荐哪种对象),这将变得非常简单:

class app():

    def __init__(self,master):
        ...
        self.popup = None

    def searchmenu(self):
        if self.popup is None:
            self.popup = Demo()

虽然一旦创建的窗口被销毁,但这不允许重新打开它,因此您可能还想检查顶部是否仍然存在winfo_exists()

def searchmenu(self):
    if self.popup is None or not self.popup.top.winfo_exists():
        self.popup = Demo()

编辑:如果弹出窗口已经打开,那么按下按钮应该lift它到窗口堆栈的顶部:

def searchmenu(self):
    if self.popup is None or not self.popup.top.winfo_exists():
        self.popup = Demo()
    else:
        self.popup.top.lift(self.master)