0

I tested the code in this answer and it works just fine.

The code creates a Application class like this:

class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)

and creates an instance with:

root = Tk()
app = Application(master=root)

However, there is one thing I do not understand in it: why the constructor takes as an argument a None object def __init__(self, master=None): but he calls the Application() class he passes it a root=Tk() instance ?

Community
  • 1
  • 1
  • 1
    `master=None` means if the calling party does not supply the parameter, assume it has the value None. – Selçuk Cihan Apr 17 '15 at 08:35
  • @SelçukCihan: the question is *why use that here*. – Martijn Pieters Apr 17 '15 at 08:37
  • 1
    TkInter has a lot of unique conventions of its own. It's conventional to write `Frame` subclasses with `master=None`, even if you're only going to call them in one place in the code, and that one place is passing a value. But this isn't _completely_ useless; you might want to test the `Frame` somewhere besides the main app, or you might change your top-level code some day… – abarnert Apr 17 '15 at 08:38

1 Answers1

2

The class copies the Frame constructor; it too takes an optional master argument. You don't have to pass in a master widget, even though here the code does pass one in. See the *frame section of An introduction to Tkinter:

Frame(master=None, **options) (class)
A widget container.

The tkinter documentation examples include the same pattern:

from Tkinter import *

class Application(Frame):
    # ...

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

root = Tk()
app = Application(master=root)

Doing so makes your code more flexible; you can now create an Application instance without a master, and pass it to code that takes any Tk object to bind at a later time.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I understand now your explanation. Thank you very much. But there is one last problem in this program: he declares `class Application(Frame)` whereas he executes it by passing it a Tk() object and not a Frame. Why this contradiction works and Python accepts it ? –  Apr 17 '15 at 08:44
  • @Nakkini: `Application` is a subclass of `Frame`; that does not mean that the initialiser only takes frames. The two concepts are entirely orthogonal. – Martijn Pieters Apr 17 '15 at 08:46
  • @Nakkini: you are confusing class inheritance with type declarations, I think. Python doesn't have any of the latter. – Martijn Pieters Apr 17 '15 at 08:46
  • what is orthogonal concepts ? –  Apr 17 '15 at 08:47
  • @Nakkini: they are at right angles to each other; e.g. the two concepts are distinct and different. – Martijn Pieters Apr 17 '15 at 08:50