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 = Timer.new(duration, nTimes, proc {command})

To start the timer, use the method ‘start’ as follows:
my_timer.start
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:

my_timer.wait

You can see an example of using two timers in the following code from the function ‘show_solution”  in my Klotski puzzle solver

  my_timer=TkTimer.new(1, 1500, proc {move_piece 'move'=>[3,1,1,0]})
  my_timer.start
  my_timer.wait
  my_timer=TkTimer.new(1, 1000, proc {move_piece 'move'=>[3,1,0,1]})
  my_timer.start
  my_timer.wait

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.

Advertisements