| 11.3 Details of the Caps Example |
|
|
This section dissects the Caps example, Script S11.1a, to show how programmers use widgets. The script places a text entry area and two buttons in the root window. The text entry area is controlled by an entry widget. Widgets of this type can take keyboard input from the user and echo it on the screen. They permit the user to perform simple editing operations. These things happen by default. They can also cause a variable's contents to be kept current with the text as the user enters it. For this to happen, the name of the variable must be declared with a -textvariable option. Here is the creation of the entry widget as it appears in the Caps script. entry .entry -textvariable EntryThe top-level Entry variable is not only updated whenever the user edits the text entry on the screen but the opposite is also true. Whenever the Entry variable is changed, the screen will reflect the change. After it is created, the entry widget is immediately displayed on the screen with this command: pack .entry Each button has an event handler associated with it that is triggered when the user clicks on the button. For the button labelled "Caps," the event handler is the following script. set Entry [string toupper $Entry]where the variable being processed is the same top-level Entry that the .entry widget keeps current. Binding this event handler to the event of a mouse click over a button is done with the -command option to the button widget maker. Another option, -text, is used to declare the label. Here are the commands that create the .edit_button button and map it to the screen.
button .edit_button -text Caps -command { set Entry [string toupper $Entry] }
pack .edit_button
The effect of clicking this button, of course, is to make all letters in the
Entry variable uppercase. Because of the way this variable is
linked to the .edit_button button, the string entered by the user
shows the same alteration.
The button labelled "Quit" has a very simple event handler associated with it. Here are the commands that create this button and map it to the screen.
button .quit_button -text Quit -command { quit }
pack .quit_button
This event handler merely executes a predefined procedure. Here is the
implementation of that procedure.
proc quit {} {
global Entry
destroy .entry .edit_button .quit_button
unset Entry
}
This procedure merely gets rid of the three widgets and the top-level
variable created by the initialization script. It does not exit the
Tk interpreter.
|
Author's Home Page |
|
Order from Amazon. |