Ruby TK – Events, Timers

Widget Events

Existing widgets will change as a result of an event, such as mouse-clicks, cursor movements and user input. When an event is fired, a callback function is invoked.

To bind an event to a widget, you would use the bind function of the widget using the function:

bind <event>, proc {command}

For example:

bind "1", proc {puts "Hello, world"}

Time Events

There is another sort of event to be used when a duration of time passes. To bind such an event, you should use a Timer object defined in ‘tk/timer’.

The syntax for creation of a timer event is:

my_timer =, nTimes, proc {command})

To start the timer, use the method ‘start’ as follows:
Timer object start as the method ‘start’ is invoked. Commands following the timer start are performed simultaneously with the command passed to the object. If you don’t want other actions taking place while the timer perform its task, you can use the method:


You can see an example of using two timers in the following code from the function ‘show_solution”  in my Klotski puzzle solver, 1500, proc {move_piece 'move'=>[3,1,1,0]})
  my_timer.wait, 1000, proc {move_piece 'move'=>[3,1,0,1]})

The code above getw the big square out of the frame. The square moves down 3 postions, and the 2 positions to the right.

The full can be downloaded from here.