2011-02-09 17 views
0

編輯: 讓我包含我的代碼,以便我可以得到一些特定的幫助。如何在它調用的函數完成後關閉Toplevel窗口?

import Tkinter 

def goPush(): 
    win2=Tkinter.Toplevel() 
    win2.geometry('400x50') 
    Tkinter.Label(win2,text="If you have prepared as Help describes select Go otherwise select Go Back").pack() 
    Tkinter.Button(win2,text="Go",command=bounceProg).pack(side=Tkinter.RIGHT,padx=5) 
    Tkinter.Button(win2, text="Go Back", command=win2.destroy).pack(side=Tkinter.RIGHT) 

def bounceProg(): 
    d=1 
    print d 
root=Tkinter.Tk() 
root.geometry('500x100') 
Tkinter.Button(text='Go', command=goPush).pack(side=Tkinter.RIGHT,ipadx=50) 
root.mainloop() 

所以當你運行程序時,它會打開一個窗口,說Go。然後Go會打開一個窗口,詢問您是否閱讀了幫助文件(我沒有在此代碼示例中提供),並提供Go Back(返回)和Go。當你選擇Go時,它調用打印1的函數。打印1後,我想讓窗口關閉返回到包含Go按鈕的原始窗口。我該如何做這樣的事情?

回答

2

@Kosig它不會退出根目錄。 IE瀏覽器。 self.foo = tk.Toplevel(self)然後self.foo.destroy()

例如:

class Foo(tk.Frame): 
    """Foo example""" 

    def __init__(self, master=None): 
     """Draw Foo GUI""" 
     tk.Frame.__init__(self, master) 
     self.grid() 
     self.draw_window_bar() 

    def draw_window_bar(self): 
     """Draw bar TopLevel window""" 
     self.window_bar = tk.Toplevel(self) 
     # Some uber-pythonian code here... 
     ask_yes_or_no = messagebox.askyesno('Brian?', 'Romani Ite Domum') 
     if not ask_yes_or_no: 
      self.window_bar.destroy() 

您有一個主對象,這是富。 Foo有一個主窗口(稱爲「框架」),它從tk.Frame獲得。之後,所有的Toplevel窗口(框架)必須在其中創建。所以,這裏的新窗口是self.window_bar,它的所有「對象」都在那裏,包括銷燬它的方法(self.window_bar.destroy())。您可以從代碼的任何部分調用self.window_bar.destroy(),但在用戶單擊「否」後調用它。

+0

但是,如何在函數完成後將其銷燬? – Kosig 2011-02-10 02:28:56

+0

你什麼都沒有。你改變你的「去」按鈕,所以它調用另一個函數,調用你的`bounceProg`函數,_then_調用`destroy`在你的窗口。 – user336851 2011-02-10 02:41:47

2

如果使用Toplevel命令創建頂層窗口,則使用窗口對象的destroy方法銷燬該窗口。例如:

import Tkinter as tk 

class MyToplevel(tk.Toplevel): 
    def __init__(self, title="hello, world", command=None): 
     tk.Toplevel.__init__(self) 
     self.wm_title(title) 
     button = tk.Button(self, text="OK", command=lambda toplevel=self: command(toplevel)) 
     button.pack() 

if __name__ == "__main__": 
    def go(top): 
     print "my work here is done" 
     top.destroy() 

    app = tk.Tk() 
    t = MyToplevel(command=go) 
    t.wm_deiconify() 
    app.mainloop() 
相關問題