pythonware.com products ::: library ::: search ::: daily Python-URL!

Library

An Introduction to Tkinter

More on widget names :::

A Django site.
   

More on widget names

Back   Next   

 More on widget names

Another source of confusion, especially for those who have some experience of programming Tk using Tcl, is Tkinter's notion of the widget name. In Tcl, you must explicitly name each widget. For example, the following Tcl command creates a Button named "ok", as a child to a widget named "dialog" (which in turn is a child of the root window, ".").

    button .dialog.ok

The corresponding Tkinter call would look like:

    ok = Button(dialog)

However, in the Tkinter case, ok and dialog are references to widget instances, not the actual names of the widgets. Since Tk itself needs the names, Tkinter automatically assigns a unique name to each new widget. In the above case, the dialog name is probably something like ".1428748," and the button could be named ".1428748.1432920". If you wish to get the full name of a Tkinter widget, simply use the str function on the widget instance:

    >>> print str(ok)
    .1428748.1432920

(if you print something, Python automatically uses the str function to find out what to print. But obviously, an operation like "name = ok" won't do the that, so make sure always to explicitly use str if you need the name).

If you really need to specify the name of a widget, you can use the name option when you create the widget. One (and most likely the only) reason for this is if you need to interface with code written in Tcl.

In the following example, the resulting widget is named ".dialog.ok" (or, if you forgot to name the dialog, something like ".1428748.ok"):

    ok = Button(dialog, name="ok")

To avoid conflicts with Tkinter's naming scheme, don't use names which only contain digits. Also note that name is a "creation only" option; you cannot change the name once you've created the widget.

Back   Next