Tkinter: Do you really need a "root"?

Russell E. Owen no at spam.invalid
Mon Jun 9 17:13:40 EDT 2003


In article <c281f461.0306071450.553776ea at posting.google.com>,
 bobsmith327 at hotmail.com (Bob Smith) wrote:

>Hi.  I'm just starting to learn to use the Tkinter module for creating
>GUIs.  I'm using a tutorial that gives a basic starting program of:
>
>from Tkinter import *
>root = Tk()
>app = Frame(root)
>root.mainloop()
>
>But do I really need root?...

In general, I suggest you always specify the master when you create a 
widget or a new widget class (such as the example below). That way your 
widgets act just like Tkinter widgets: they can be put into any other 
widget or toplevel window. It makes your code maximally flexible and 
extensible.

If you explicitly create a root then you are all set to specify it as 
the master of whatever you want to put into the root window. Then if you 
change your mind and want to put those widgets into some other container 
(such as a different toplevel window or a frame or...) you are all set.

A typical GUI application will an extensive hierarchy of widgets 
containing other widgets -- including multiple windows (Toplevel 
widgets).

The following is typical code for creating your own widget class that 
acts much like a Tkinter widget:

class MyFancyWdg(Tkinter.Frame):
  def __init__(self, master):
    # my master is whatever the user specified
    Tkinter.Frame.__init__(master)

    # any widgets I create to put inside myself
    # should use me (self) as the master
    self.somewdg = Tkinter.Label(self, ...)
    self.somewdg.grid(...)
    self.someotherwidg = Tkinter.Text(self, ...)
    self.someotherwdg.grid(...)
    ...

-- Russell




More information about the Python-list mailing list