Tkinter Confusion

7stud bbxx789_05ss at yahoo.com
Mon Feb 18 04:47:41 EST 2008


On Feb 18, 1:41 am, "peterca... at gmail.com" <peterca... at gmail.com>
wrote:
> Most of the other questions have already been answered, so I'll tackle
> this one:
>
> On Feb 17, 8:36 pm, MartinRineh... at gmail.com wrote:
>
> > Google's great, but it has no truth meter. Do I inherit from Frame? Or
> > is that a big mistake. (Both positions repeated frequently.)
>
> Inherit from Frame if you want your class to be a packable widget. If
> you only intend to pack widgets in a supplied container, no need to
> subclass Frame...
>
> Pete

Whether you should inherit from Frame or not depends on wether you
want to write your code with a procedural style or with an object
oriented style.  You can write Tkinter programs with a procedural
style(see previous examples), or you can write them with an object
oriented style:


import Tkinter as tk

class MyLabelFrame(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.config(background='green')

        label1 = tk.Label(self, text='hello world', background='gray')
        label2 = tk.Label(self, text='goodbye', background='gray')

        label1.pack()  #makes label visible
        label2.pack()  #makes label visible


class MyButtonFrame(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.config(background='black', padx=20, pady=20)

        button1 = tk.Button(self, text='suprise 1',
command=self.sayhi)
        button2 = tk.Button(self, text='suprise 2',
command=self.saybye)

        button1.pack()
        button2.pack()

    def sayhi(self):
        print 'hi'

    def saybye(self):
        print 'bye'




class MyApp(object):
    def __init__(self, *frames):
        root = tk.Tk()
        root.geometry('600x400')
        root.config(background='red')

        frame1 = MyLabelFrame(root)
        frame2 = MyButtonFrame(root)

        frame1.pack(side=tk.TOP)
        frame2.pack(side=tk.BOTTOM)

        root.mainloop()

app = MyApp()


If you don't know what object oriented programming is, then stick to
the simplicity of the procedural style in the previous examples.



More information about the Python-list mailing list