Previous section   Next section

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 31.  The Entry Widget

Using Entry Widgets

The entry widget supports editing, scrolling, and selections, which make it more complex than label or message widgets. Fortunately, the default settings for an entry widget make it usable right away. You click with the left button to set the insert point and then type in text. Text is selected by dragging out a selection with the left button. The entry can be scrolled horizontally by dragging with the middle mouse button.

One common use of an entry widget is to associate a label with it, and a command to execute when <Return> is pressed in the entry. The grid geometry manager is ideal for lining up several entries and their labels. This is implemented in the following example:

Example 31-1 A command entry.


foreach field {Name Address1 Address2 Phone} {
   label .l$field -text $field -anchor w
   entry .e$field -textvariable address($field) -relief sunken
   grid .l$field .e$field -sticky news
   bind .e$field <Return> UpdateAddress

Example 31-1 creates four entries that are linked to variables with the textvariable attribute. The variables are elements of the address array. The -relief sunken for the entry widget sets them apart visually. Widget relief is described in more detail on page 530. The Tcl command UpdateAddress is bound to the <Return> keystroke. The UpdateAddress procedure, which is not shown, can get the current values of the entry widgets through the global array address.

Tips for Using Entry Widgets


If you are displaying long strings in an entry, you can use the following command to keep the end of the string in view. The command requests that all the string be off screen to the left, but the widget implementation fills up the display; the scrolling is limited so that the tail of the string is visible:

$entry xview moveto 1.0

The show attribute is useful for entries that accept passwords or other sensitive information. If show is not empty, it is used as the character to display instead of the real value:

$entry config -show *

The state attribute determines if the contents of an entry can be modified. Set the state to disabled to prevent modification and set it to normal to allow modification.

$entry config -state disabled ;# read-only
$entry config -state normal   ;# editable

The middle mouse button (<Button-2>) is overloaded with two functions. If you click and release the middle button, the selection is inserted at the insert cursor. The location of the middle click does not matter. If you press and hold the middle button, you can scroll the contents of the entry by dragging the mouse to the left or right.

      Previous section   Next section