Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

tkinter

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?

like image 741
user62453 Avatar asked Dec 05 '13 22:12

user62453


1 Answers

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()
like image 104
furas Avatar answered Nov 20 '22 05:11

furas