为什么我们通过根窗口的窗口'创建Toplevel窗口时的属性?

时间:2014-07-21 17:03:19

标签: python tkinter

我正在学习如何使用带有OOP方法的tkinter创建父窗口和子窗口,但是在创建Toplevel窗口时没有完全理解传递父窗口的'window'属性的原因。见下文......

from tkinter import *

class Main():

    def __init__(self, master):
        self.master = master
        self.master.title("Main Window")

        self.button1 = Button(self.master, text="Click Me 1", command = self.Open1)
        self.button1.grid(row=0, column=0, sticky=W)
        self.button2 = Button(self.master, text="Click Me 2", command = self.Open2)
        self.button2.grid(row=0, column=2, sticky=W)
        self.button3 = Button(self.master, text="Close", command = self.Close)
        self.button3.grid(row=1, column=0, sticky=W)


    def Open1(self):
        second_window = Toplevel(self.master)
        window2 = Second(second_window)

    def Open2(self):
        third_window = Toplevel(self.master)
        window3 = Third(third_window)

    def Close(self):
        self.master.destroy()


class Second():

    def __init__(self, master):
        self.second_window = second_window
        self.master.title("Second Window")

class Third():

    def __init__(self, master):
        self.master = master
        self.master.title("Third Window")


root_window = Tk()
root_window.geometry("200x85")
main_window = Main(root_window)
root_window.mainloop()

然而,两个顶级窗口的创建也可以在没有参数的情况下编写......它似乎产生了相同的结果:

def Open1(self):
            second_window = Toplevel()
            window2 = Second(second_window)

        def Open2(self):
            third_window = Toplevel()
            window3 = Third(third_window)

那么为什么我们经常在实例化顶级窗口时传递这个根窗口的属性?

1 个答案:

答案 0 :(得分:1)

除根窗口外的所有小部件都需要父级。这就是tkinter的工作原理。如果您没有传入父级,则根窗口是默认的。

python的禅说明语比隐含更好。明确地传递它可以防止人们不得不提出这个问题,并使代码更容易理解。