Next / Previous / Contents / TCC Help System / NM Tech homepage

5. Standard attributes

Before we look at the widgets, let's take a look at how some of their common attributes—such as sizes, colors and fonts—are specified.

5.1. Dimensions

Various lengths, widths, and other dimensions of widgets can be described in many different units.

  • If you set a dimension to an integer, it is assumed to be in pixels.

  • You can specify units by setting a dimension to a string containing a number followed by:

    cCentimeters
    iInches
    mMillimeters
    pPrinter's points (about 1/72")

5.2. The coordinate system

As in most contemporary display systems, the origin of each coordinate system is at its upper left corner, with the x coordinate increasing toward the right, and the y coordinate increasing toward the bottom:

The base unit is the pixel, with the top left pixel having coordinates (0,0). Coordinates that you specify as integers are always expressed in pixels, but any coordinate may be specified as a dimensioned quantity; see Section 5.1, “Dimensions”.

5.3. Colors

There are two general ways to specify colors in Tkinter.

  • You can use a string specifying the proportion of red, green, and blue in hexadecimal digits:

    #rgbFour bits per color
    #rrggbbEight bits per color
    #rrrgggbbbTwelve bits per color

    For example, '#fff' is white, '#000000' is black, '#000fff000' is pure green, and '#00ffff' is pure cyan (green plus blue).

  • You can also use any locally defined standard color name. The colors "white", "black", "red", "green", "blue", "cyan", "yellow", and "magenta" will always be available. Other names may work, depending on your local installation.

5.4. Type fonts

Depending on your platform, there may be up to three ways to specify type style.

  • As a tuple whose first element is the font family, followed by a size in points, optionally followed by a string containing one or more of the style modifiers bold, italic, underline, and overstrike.

    Examples: ("Helvetica", "16") for a 16-point Helvetica regular; ("Times", "24", "bold italic") for a 24-point Times bold italic.

  • You can create a “font object” by importing the tkFont module and using its Font class constructor:

    import tkFont
    
    font = tkFont.Font ( option, ... )
    

    where the options include:

    family The font family name as a string.
    size The font height as an integer in points. To get a font n pixels high, use -n.
    weight"bold" for boldface, "normal" for regular weight.
    slant "italic" for italic, "roman" for unslanted.
    underline 1 for underlined text, 0 for normal.
    overstrike 1 for overstruck text, 0 for normal.

    For example, to get a 36-point bold Helvetica italic face:

        helv36 = tkFont.Font ( family="Helvetica",
            size=36, weight="bold" )
    
  • If you are running under the X Window System, you can use any of the X font names. For example, the font named "-*-lucidatypewriter-medium-r-*-*-*-140-*-*-*-*-*-*" is the author's favorite fixed-width font for onscreen use. Use the xfontsel program to help you select pleasing fonts.

To get a list of all the families of fonts available on your platform, call this function:

    tkFont.families()

The return value is a list of strings. Note: You must create your root window before calling this function.

These methods are defined on all Font objects:

.actual ( option=None )

If you pass no arguments, you get back a dictionary of the font's actual attributes, which may differ from the ones you requested. To get back the value of an attribute, pass its name as an argument.

.cget ( option )

Returns the value of the given option.

.configure ( option, ... )

Use this method to change one or more options on a font. For example, if you have a Font object called titleFont, if you call titleFont.configure ( family="times", size=18 ), that font will change to 18pt Times and any widgets that use that font will change too.

.copy()

Returns a copy of a Font object.

.measure ( text )

Pass this method a string, and it will return the number of pixels of width that string will take in the font. Warning: some slanted characters may extend outside this area.

.metrics ( option )

If you call this method with no arguments, it returns a dictionary of all the font metrics. You can retrieve the value of just one metric by passing its name as an argument. Metrics include:

ascent Number of pixels of height between the baseline and the top of the highest ascender.
descent Number of pixels of height between the baseline and the bottom of the lowest ascender.
fixed This value is 0 for a variable-width font and 1 for a monospaced font.
linespace Number of pixels of height total. This is the leading of type set solid in the given font.

5.5. Anchors

The Tkinter package defines a number of anchor constants that you can use to control where items are positioned relative to their context. For example, anchors can specify where a widget is located inside a frame when the frame is bigger than the widget.

These constants are given as compass points, where north is up and west is to the left. We apologize to our Southern Hemisphere readers for this Northern Hemisphere chauvinism.

The anchor constants are shown in this diagram:

For example, if you create a small widget inside a large frame and use the anchor=SE option, the widget will be placed in the bottom right corner of the frame. If you used anchor=N instead, the widget would be centered along the top edge.

Anchors are also used to define where text is positioned relative to a reference point. For example, if you use CENTER as a text anchor, the text will be centered horizontally and vertically around the reference point. Anchor NW will position the text so that the reference point coincides with the northwest (top left) corner of the box containing the text. Anchor W will center the text vertically around the reference point, with the left edge of the text box passing through that point, and so on.

5.6. Relief styles

The relief style of a widget refers to certain simulated 3-D effects around the outside of the widget. Here is a screen shot of a row of buttons exhibiting all the possible relief styles:

The width of these borders depends on the borderwidth attribute of the widget. The above graphic shows what they look like with a 5-pixel border; the default border width is 2.

5.7. Bitmaps

For bitmap options in widgets, these bitmaps are guaranteed to be available:

The graphic above shows Button widgets bearing the standard bitmaps. From left to right, they are "error", "gray75", "gray50", "gray25", "gray12", "hourglass", "info", "questhead", "question", and "warning".

You can use your own bitmaps. Any file in .xbm (X bit map) format will work. In place of a standard bitmap name, use the string "@" followed by the pathname of the .xbm file.

5.8. Cursors

There are quite a number of different mouse cursors available. Their names and graphics are shown here. The exact graphic may vary according to your operating system.

arrow man
based_arrow_down middlebutton
based_arrow_up mouse
boat pencil
bogosity pirate
bottom_left_corner plus
bottom_right_corner question_arrow
bottom_side right_ptr
bottom_tee right_side
box_spiral right_tee
center_ptr rightbutton
circle rtl_logo
clock sailboat
coffee_mug sb_down_arrow
cross sb_h_double_arrow
cross_reverse sb_left_arrow
crosshair sb_right_arrow
diamond_cross sb_up_arrow
dot sb_v_double_arrow
dotbox shuttle
double_arrow sizing
draft_large spider
draft_small spraycan
draped_box star
exchange target
fleur tcross
gobbler top_left_arrow
gumby top_left_corner
hand1 top_right_corner
hand2 top_side
heart top_tee
icon trek
iron_cross ul_angle
left_ptr umbrella
left_side ur_angle
left_tee watch
leftbutton xterm
ll_angle X_cursor
lr_angle  

5.9. Images

There are three general methods for displaying graphic images in your Tkinter application.

5.9.1. The BitmapImage class

To display a two-color image in the .xbm format, you will need this constructor:

    BitmapImage ( file=f[, background=b][, foreground=c] )

where f is the name of the .xbm image file.

Normally, foreground (1) bits in the image will be displayed as black pixels, and background (0) bits in the image will be transparent. To change this behavior, use the optional background=b option to set the background to color b, and the optional foreground=c option to set the foreground to color c. For color specification, see Section 5.3, “Colors”.

This constructor returns a value that can be used anywhere Tkinter expects an image. For example, to display an image as a label, use a Label widget (see Section 11, “The Label widget”) and supply the BitmapImage object as the value of the image option:

    logo = BitmapImage("logo.xbm", foreground='red')
    Label ( image=logo ).grid()

5.9.2. The PhotoImage class

To display a color image in .gif, .pgm, or .ppm format, you will need this constructor:

    PhotoImage ( file=f )

where f is the name of the image file. The constructor returns a value that can be used anywhere Tkinter expects an image.

5.10. Geometry strings

A geometry string is a standard way of describing the size and location of a top-level window on a desktop.

A geometry string has this general form:

    "wxh±x±y"

where:

  • The w and h parts give the window width and height in pixels. They are separated by the character "x".

  • If the next part has the form +x, it specifies that the left side of the window should be x pixels from the left side of the desktop. If it has the form -x, the right side of the window is x pixels from the right side of the desktop.

  • If the next part has the form +y, it specifies that the top of the window should be y pixels below the top of the desktop. If it has the form -y, the bottom of the window will be y pixels above the bottom edge of the desktop.

For example, a window created with geometry="120x50-0+20" would be 120 pixels wide by 50 pixels high, and its top right corner will be along the right edge of the desktop and 20 pixels below the top edge.

5.11. Window names

The term window describes a rectangular area on the desktop.

  • A top-level or root window is a window that has an independent existence under the window manager. It is decorated with the window manager's decorations, and can be moved and resized independently. Your application can use any number of top-level windows.

  • The term “window” also applies to any widget that is part of a top-level window.

Tkinter names all these windows using a hierarchical window path name.

  • The root window's name is ".".

  • Child windows have names of the form ".n", where n is some integer in string form. For example, a window named ".135932060" is a child of the root window (".").

  • Child windows within child windows have names of the form "p.n" where p is the name of the parent window and n is some integer. For example, a window named ".135932060.137304468" has parent window ".135932060", so it is a grandchild of the root window.

  • The relative name of a window is the part past the last "." in the path name. To continue the previous example, the grandchild window has a relative name "137304468".

The path name for any widget w can be determined by calling str(w).

See also Section 25, “Universal widget methods” for methods you can use to operate on window names, especially the .winfo_name, .winfo_parent, and .winfo_pathname methods.

5.12. Cap and join styles

For pleasant and effective rendering of diagrams, sometimes it is a good idea to pay attention to cap and join styles.

  • The cap style of a line is the shape of the end of the line. Styles are:

    • BUTT: The end of the line is cut off square at a line that passes through the endpoint.

    • PROJECTING: The end of the line is cut off square, but the cut line projects past the endpoint a distance equal to half the line's width.

    • ROUND: The end describes a semicircle centered on the endpoint.

  • The join style describes the shape where two line segments meet at an angle.

    • ROUND: The join is a circle centered on the point where the adjacent line segments meet.

    • BEVEL: A flat facet is drawn at an angle intermediate between the angles of the adjacent lines.

    • MITER: The edges of the adjacent line segments are continued to meet at a sharp point.

This illustration shows Tkinter's cap and join options. Small red squares indicate the nominal endpoints of the two connected line segments.

5.13. Dash patterns

A number of widgets allow you to specify a dashed outline. The dash and dashoffset options give you fine control over the exact pattern of the dashes.

dash

This option is specified as a tuple of integers. The first integer specifies how many pixels should be drawn. The second integer specifies how many pixels should be skipped before starting to draw again, and so on. When all the integers in the tuple are exhausted, they are reused in the same order until the border is complete.

For example, dash=(3,5) produces alternating 3-pixel dashes separated by 5-pixel gaps. A value of dash=(7,1,1,1) produces a dash-and-dot pattern, with the dash seven times as long as the dot or the gaps around the dot. A value of dash=(5,) produces alternating five-pixel dashes and five-pixel gaps.

dashoff

To start the dash pattern in a different point of cycle instead of at the beginning, use an option of dashoff=n, where n is the number of pixels to skip at the beginning of the pattern.

For example, for options dash=(5, 1, 2, 1) and dashoff=3, the first pattern produced will be: 2 on, 1 off, 2 on, and 1 off. Subsequent patterns will be 5 on, 1 off, 2 on, and 1 off. Here is a screen shot of a line drawn with this combination of options:

5.14. Matching stipple patterns

This may seem like an incredibly picky style point, but if you draw a graphic that has two objects with stippled patterns, a real professional will make sure that the patterns align along their boundary.

Here is an example. The left-hand screen shot shows two adjacent 100×100 squares stippled with the “gray12” pattern, but the right-hand square is offset vertically by one pixel. The short black line in the center of the figure is drawn along the boundary of the two figures.

Misaligned stipples. Properly aligned stipples.

The second screen shot is the same, except that the two 100×100 squares have their stipple patterns lined up.

In practice, this arises in two situations. The alignment of large stippled areas is controlled by an option named offset. For figures with stippled outlines, the outlineoffset option controls their alignment. Both options have values of one of these forms:

  • "x,y": Offset the stipple patterns by this x and y value relative to the top-level window or to the canvas's origin.

  • "#x,y": For objects on a canvas, use offset x and y relative to the top-level window.

  • "ne", "se", "sw", "nw": Align a corner of the stipple pattern with the corresponding corner of the containing object. For example, "ne" means that the top left corner of the stipple pattern coincides with the top left corner of the area to be stippled.

  • "n", "e", "s", "w": Align the stipple pattern with the center of one side of the containing object. For example, "e" means the center of the stipple pattern will coincide with the center of the right side of the area to be stippled.

  • "center": Align the center of the stipple pattern with the center of the containing object.