What does Frame.__init__ do?

2019-03-22 02:13发布

问题:

in the following code, line 5, what does Frame.__init__ do? Could someone explain the concept behind it? Thanks a lot!

from Tkinter import *
class AppUI(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master, relief=SUNKEN, bd=2)
        [...]

Edit: Full Code with correct indention here

回答1:

The class AppUI is based on the class Frame from Tkinter. This means the AppUI class is a type of Frame but with some behaviors slightly different or customized. Which means that the methods of the AppUI class may need to (in fact, usually will need to) call code from the Frame class. That is, AppUI wants to do the same thing as the Frame class, and also something else. That's what's happening here: when you instantiate an AppUI, you want it to be initialized as a Frame first, and then perform the AppUI-specific initialization.

Here AppUI explicitly calls its parent class's __init__() method.

You can also do this using the super() function—and usually you would; it's basically required in multiple-inheritance scenarios. But because Tkinter uses "old-style classes", you have to do it the old way here.



回答2:

the concept behind is that Tkinter provides a special widget type for menus, StatusBar is inherited from the Frame widget. while you use that, i think the purpose is that It wil not increases the risk that your additional methods conflict with attributes or methods used by Tkinter

see: http://effbot.org/tkinterbook/tkinter-application-windows.htm