0

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

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

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()
4

1 回答 1

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)
于 2016-02-25T21:22:44.123 回答