Previous section   Next section

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

Table of Contents
Chapter 44.  C Programming and Tcl

The Event Loop

An event loop is used to process window system events and other events like timers and network sockets. The different event types are described later. All Tk applications must have an event loop so that they function properly in the window system environment. Tk provides a standard event loop with the Tk_MainLoop procedure, which is called at the end of Tk_Main. The wish shell provides an event loop automatically. The tclsh shell does not, although you can add an event loop using pure Tcl as shown in Example 16-2 on page 220.

Some applications already have their own event loop. You have two choices if you want to add Tk to such an application. The first is to modify the existing event loop to call Tcl_DoOneEvent to process any outstanding Tcl events. The unix directory of the source distribution has a file called XtTest.c that adds Tcl to an Xt (i.e., Motif) application. The other way to customize the event loop is to make your existing events look like Tcl event sources, and register them with the event loop. Then you can just use Tk_Main. There are four event classes, and they are handled in the following order by Tcl_DoOneEvent:

  • Window events. Use the Tk_CreateEventHandler procedure to register a handler for these events. Use the TCL_WINDOW_EVENTS flag to process these in Tcl_DoOneEvent.

  • File events. Use these events to wait on slow devices and network connections. On UNIX you can register a handler for all files, sockets, and devices with Tcl_CreateFileHandler. On Windows and Macintosh, there are different APIs for registration because there are different system handles for files, sockets, and devices. On all platforms you use the TCL_FILE_EVENTS flag to process these handlers in Tcl_DoOneEvent.

  • Timer events. You can set up events to occur after a specified time period. Use the Tcl_CreateTimerHandler procedure to register a handler for the event. Use the TCL_TIMER_EVENTS flag to process these in Tcl_DoOneEvent.

  • Idle events. These events are processed when there is nothing else to do. Virtually all the Tk widgets use idle events to display themselves. Use the Tcl_DoWhenIdle procedure to register a procedure to call once at the next idle time. Use the TCL_IDLE_EVENTS flag to process these in Tcl_DoOneEvent.

      Previous section   Next section