2

I would like to create a Button that open a new tkinter window when it is pushed. I have already found a solution in another post but in this example i would like to desactivate the button when a new window is open . Here is what i have (test code) :

import Tkinter as tk

def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()

root.mainloop()

so i would like to desactivate the button bwhile a new window is still open.

Thanks.

1 Answer 1

6

There are a couple different ways that first come to mind.

One way would be just to disable interaction with the entire window, this would be done by using the .grab_set() method on your newly created window.

def create_window():
    window = tk.Toplevel(root)
    window.grab_set()

This method means the created window is now focused on, when the focused window is destroyed you will then again be able to interact with other windows.

Another way would be to have your function create_window() take the button as an input, then use the .configure(state="disabled") on the button

def create_window(button):
    window = tk.Toplevel(root)
    button.configure(state="disabled")

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=lambda: create_window(b))
b.pack()

Please note that since your function needs an input now, you need to use command= lambda:create_window(b) so then the create_window() isn't run when the button is created.

However now you would have to write another function that will change the buttons state back to .configure(state="normal") when the new window is destroyed. e.g.

def create_window(button):
    window = tk.Toplevel(root)

    def on_close():
        button.configure(state="normal")
        window.destroy()

    button.configure(state="disabled")

    window.protocol("WM_DELETE_WINDOW", on_close)
3
  • 1
    Thanks you ! i think i will probably use the second method even if it seems to be more difficult to implement but i will probably need to interact with the principal window
    – Lucas
    Commented May 16, 2019 at 14:51
  • No problem, I updated my answer because I realized that this may cause some unwanted effects. It just explains how you might enable the button again.
    – MatthewG
    Commented May 16, 2019 at 14:56
  • Yeah i was implementing it in my code and i just realized that. Thanks !
    – Lucas
    Commented May 16, 2019 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.