grab_set in tkinter window

Viewed 14380

I've seen many examples of grab_set() being used for modal windows for tkinter but I can't get it to work for my application. I am creating a second window as my 'Settings' window which is called from the Menu of the main application.

example:

import tkinter as tk

class Main(tk.Tk):

    def __init__(self,*args, **kwargs):
        tk.Tk.__init__(self,*args, *kwargs)

        button = tk.Button(self,text="second window", command=lambda:Settings())
        button.pack()


class Settings(tk.Tk):

    def __init__(self,*args, **kwargs):
        tk.Tk.__init__(self,*args, *kwargs)
        button = tk.Button(self,text="quit", command=lambda: quit())
        button.pack()
        self.grab_set()

if __name__ == "__main__":
    app = Main()
    app.mainloop()

Right now I can still click the 'Settings' button to create as many instances of Settings as the pc would allow. How do I restrict clickability to the main application window until the second one is closed first?

4 Answers

Try adding the following line after the line containing the grab_set method:

self.wait_window(self)

You need to allow focus with takefocus = True and you give the focus to it with focus_set()

def __init__(self, *args, **kwargs):
    Toplevel.__init__(self, *args, **kwargs)
    self.takefocus = True
    self.focus_set()
Related