Search code examples
pythontkinterpack

Differentiation between two using pack() in python


I have two code following the first one:

from tkinter import *
root = Tk()
class App(Frame):
    def __init__(self, master):
        Frame.__init__(self,master)
        self.pack()
        for keyF in ('123','456','789','-0.'):
            keyFr = Frame(self).pack(side="top")
            for char in keyF:
                but = Button(keyFr, text=char).pack(side='left')    
App(root)
root.mainloop()

Result:

enter image description here

the second code:

from tkinter import *
root = Tk()
class App(Frame):
    def __init__(self, master):
        Frame.__init__(self,master)
        self.pack()
        for keyF in ('123','456','789','-0.'):
            keyFr = Frame(self)
            keyFr.pack(side="top")
            for char in keyF:
                but = Button(keyFr, text=char)
                but.pack(side='left')
App(root)
root.mainloop()

Result:

enter image description here

I do not know what is different between using pack in those codes. Could you help me explain the one?


Solution

  • This code does not do what you think:

    keyFr = Frame(self).pack(side="top")
    

    What it does is set keyFr to None. Why? In python, x().y() returns the value of y(). Therefore, Frame(self).pack(side="top") returns the value of pack(side="top"). pack(...) always returns None so keyFr is None.

    Because keyFr is none, all of the buttons in the first block of code are getting added to the root window rather than the frame.