user62453
user62453

Reputation: 225

make a button open only one window at a time (enable a button by closing a Toplevel window)

I want NewWinButton to create only one new window at a time, which means if

if NewWin.winfo_exists() == 1:
   NewWinButton.config(state='disabled')
else:
   NewWinButton.config(state='normal')

I can make this work if I add a button to the new window (QuitButton in this example):

import tkinter as tk

root = tk.Tk()
root.title('Main Window')
root.geometry('400x400')

def get_new_win():

    NewWin = tk.Toplevel(root)
    NewWin.title('New Window')
    NewWin.geometry('300x300')
    NewWinButton.config(state='disable')

    def quit_win():
        NewWin.destroy()
        NewWinButton.config(state='normal')

    QuitButton = tk.Button(NewWin,text='Quit', command=quit_win).pack()

NewWinButton = tk.Button(root,text='New Window', get_new_win).pack()

root.mainloop()

This works if and only if I use QuitButton to close the new window; however, if I use the close button in the new window, then the NewWinButton will remain 'disabled'.

Can anyone tell me how to fix this?

Upvotes: 5

Views: 8349

Answers (1)

furas
furas

Reputation: 142641

Use NewWin.protocol("WM_DELETE_WINDOW", quit_win) to assign function quit_win to the close button.

import tkinter as tk

root = tk.Tk()
root.title('Main Window')
root.geometry('400x400')

def get_new_win():

    NewWin = tk.Toplevel(root)
    NewWin.title('New Window')
    NewWin.geometry('300x300')
    NewWinButton.config(state='disable')

    def quit_win():
        NewWin.destroy()
        NewWinButton.config(state='normal')

    QuitButton = tk.Button(NewWin, text='Quit', command=quit_win)
    QuitButton.pack()

    NewWin.protocol("WM_DELETE_WINDOW", quit_win) 

NewWinButton = tk.Button(root, text='New Window', command=get_new_win)
NewWinButton.pack()

root.mainloop()

BTW:

The pack() method returns None, not a button instance:

NewWinButton = tk.Button(...).pack()

use this:

NewWinButton = tk.Button(...)
NewWinButton.pack()

Upvotes: 7

Related Questions