使按钮一次只打开一个窗口(通过关闭Toplevel窗口启用按钮)

时间:2013-12-05 22:33:05

标签: python tkinter

我希望NewWinButton一次只创建一个新窗口,这意味着

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

如果我在新窗口中添加一个按钮(在此示例中为QuitButton),我可以完成这项工作:

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

当且仅当我使用QuitButton关闭新窗口时才有效;但是,如果我在新窗口中使用关闭按钮,则NewWinButton将保持“禁用”状态。

有谁能告诉我如何解决这个问题?

1 个答案:

答案 0 :(得分:6)

使用NewWin.protocol("WM_DELETE_WINDOW", quit_win)将功能quit_win分配给关闭按钮。

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

顺便说一句:

pack()方法返回None,而非按钮实例:

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

使用它:

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