Chris
Chris

Reputation: 25

How to limit number of Toplevel windows in tkinter

I have a bit of code that creates a a top level window upon the user pressing a button.

However i would like to limit the number Top level windows to one, so the user couldn't Spam the button and open fifty windows.

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

Upvotes: 0

Views: 1364

Answers (1)

Tadhg McDonald-Jensen
Tadhg McDonald-Jensen

Reputation: 21453

If you make a reference to the Demo object you create (which I'd recommend regardless) this becomes very trivial task:

class app():

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

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

Although once the created window is destroyed this doesn't allow to reopen it, so you may want to also check if the top still exists with winfo_exists():

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

EDIT: if the popup is already open then pushing the button should lift it to the top of the window stack:

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)

Upvotes: 1

Related Questions