Using Python and tkinter, what benefit is there to using __init__ when creating a Frame in a class?

I am learning Python and tkinter by going through several tutorials (python-course.eu & effbot.org). I have come across a pair of situations and am trying to learn the reasons behind the differences.

NOTE: I found many questions regarding __init__ in class, but not __init__ in frame.

Both call a class from the main, and use a constructor (def __init__) to create an instance of the class. Am I using correct terminology?

They both create a frame; however, one uses Frame.__init__(self,parent): and the other uses Frame(master):

  • Why does the first include init in the construction of the frame?
  • Why does the second omit 'self' in the arguments when creating the frame?
  • Why does the first not use 'pack' to place, but the second does?
  • What other differences are noteworthy?

The following are MWE to produce the respective outputs.

import tkinter as tk

class Checkbar(tk.Frame):
   def __init__(self, parent=None, picks=[], side=tk.LEFT, anchor=tk.W):
      tk.Frame.__init__(self, parent)
      self.vars = []
      for pick in picks:
         var = tk.IntVar()
         chk = tk.Checkbutton(self, text=pick, variable=var)
         chk.pack(side=side, anchor=anchor, expand=tk.YES)
         self.vars.append(var)
   def state(self):
      return map((lambda var: var.get()), self.vars)

if __name__ == '__main__':
   root = tk.Tk()

   lng = Checkbar(root, ['Python', 'Ruby', 'Perl', 'C++'])
   tgl = Checkbar(root, ['English','German'])
   lng.pack(side=tk.TOP,  fill=tk.X)
   tgl.pack(side=tk.LEFT)
   lng.config(relief=tk.GROOVE, bd=2)

   def allstates(): 
      print(list(lng.state()), list(tgl.state()))
   tk.Button(root, text='Quit', command=root.destroy).pack(side=tk.RIGHT)
   tk.Button(root, text='Peek', command=allstates).pack(side=tk.RIGHT)

   root.mainloop()
   print("You've selected ", list(lng.state()))

Language Widget

import tkinter as tk

class App:
    def __init__(self, master):  

        frame = tk.Frame(master)
        frame.pack()

        self.button = tk.Button(frame, text="Quit", fg="red", command=master.destroy, padx=20)
        self.button.pack(side='left', expand=10)

        self.hi_there = tk.Button(frame, text="Hello", command=self.say_hi)
        self.hi_there.pack(side='left')

    def say_hi(self):
        print("Hi there, everyone!")

if __name__ == '__main__':
    root = tk.Tk()
    app = App(root)
    root.mainloop()

Hello Window

Thank you, kindly.

0 Comment

NO COMMENTS

LEAVE A REPLY

Captcha image