Is it necessary to call Tk() when writing a GUI app with Tkinter?

Rick Johnson rantingrickjohnson at gmail.com
Sat Mar 3 23:27:43 EST 2012


On Mar 2, 4:16 pm, John Salerno <johnj... at gmail.com> wrote:
> what is the point of creating a Frame object at all? I tried NOT
> doing it, like you said, and it seemed to work fine with my simple
> example. But is there a benefit to using a Frame object to group the
> widgets together? Or is it cleaner to just use the Tk object?

You will no doubt need to use frames to group widgets from time to
time. My previous point was simply: "don't use frames superfluously!".

Here is an example of creating a custom compound widget by sub-
classing frame (psst: this widget already exists in the Tix extension.

## START CODE ##
import Tkinter as tk
from Tkconstants import LEFT, YES, X, N

class LabelEntry(tk.Frame):
    def __init__(self, master, text='LE', **kw):
        tk.Frame.__init__(self, master, **kw)
        self.label = tk.Label(self, text=text, font=('Courier New',
12))
        self.label.pack(side=LEFT)
        self.entry = tk.Entry(self)
        self.entry.pack(side=LEFT, fill=X, expand=YES)

    def get(self):
        return self.entry.get()

    def set(self, arg):
        self.entry.delete(0, 'end')
        self.entry.set(arg)

if __name__ == '__main__':
    root = tk.Tk()
    for blah in ('   Name:', 'Address:', '  Phone:'):
        w = LabelEntry(root, text=blah)
        w.pack(fill=X, expand=YES, anchor=N, padx=5, pady=5)
    root.mainloop()
## END CODE ##



More information about the Python-list mailing list