python,如何处理多个窗口之间的事件?

时间:2016-08-18 06:00:20

标签: python user-interface tkinter

我正在使用以下示例代码生成两个窗口:

import Tkinter as tk

class Demo1:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
        self.button1.pack()
        self.frame.pack()
    def new_window(self):
        print 1
        self.newWindow = tk.Toplevel(self.master)
        print 2
        self.app = Demo2(self.newWindow)
        print 3

class Demo2:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.quitButton.pack()
        self.frame.pack()
    def close_windows(self):
        self.master.destroy()

def main(): 
    root = tk.Tk()
    app = Demo1(root)
    root.mainloop()

if __name__ == '__main__':
    main()

当调用new_window()方法时,我希望打印“1”(或者可能是“2”)。我希望在Demo2关闭时打印“3”! 但是按button1我执行了所有三个打印语句。 我怎么能处理这个?

1 个答案:

答案 0 :(得分:2)

您可以使用wait_window方法等待第二个窗口被销毁,然后再继续执行第一个窗口中的下一个语句。

我修改了您的代码以使其正常工作。希望它有所帮助 -

import Tkinter as tk

class Demo1(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.master = master
        self.frame = tk.Frame(self.master)
        self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
        self.button1.pack()
        self.frame.pack()
    def new_window(self):
        print 1
        # self.newWindow = tk.Toplevel(self.master)
        print 2
        self.app = Demo2(self).display_window()
        print 3

class Demo2:
    def __init__(self, master):
        self.master = tk.Toplevel(master)
        self.frame = tk.Frame(self.master)
        self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.master.destroy)
        self.quitButton.pack()
        self.frame.pack()

    def display_window(self):
        self.master.wait_window()
        return 0

def main(): 
    root = tk.Tk()
    app = Demo1(root)
    root.mainloop()

if __name__ == '__main__':
    main()