1#!/usr/bin/env ruby
2# This script is a re-implementation of tktimer.rb with TkTimer(TkAfter) class.
3
4require "tk"
5
6# new notation :
7#   * symbols are acceptable as keys or values of the option hash
8#   * the parent widget can be given by :parent key on the option hash
9root = TkRoot.new(:title=>'timer sample')
10label = TkLabel.new(:parent=>root, :relief=>:raised, :width=>10) \
11               .pack(:side=>:bottom, :fill=>:both)
12
13# define the procedure repeated by the TkTimer object
14tick = proc{|aobj| #<== TkTimer object
15  cnt = aobj.return_value + 5 # return_value keeps a result of the last proc
16  label.text format("%d.%02d", *(cnt.divmod(100)))
17  cnt #==> return value is kept by TkTimer object
18      #    (so, can be send to the next repeat-proc)
19}
20
21timer = TkTimer.new(50, -1, tick).start(0, proc{ label.text('0.00'); 0 })
22        # ==> repeat-interval : (about) 50 ms,
23        #     repeat : infinite (-1) times,
24        #     repeat-procedure : tick (only one, in this case)
25        #
26        # ==> wait-before-call-init-proc : 0 ms,
27        #     init_proc : proc{ label.text('0.00'); 0 }
28        #
29        # (0ms)-> init_proc ->(50ms)-> tick ->(50ms)-> tick ->....
30
31TkButton.new(:text=>'Start') {
32  command proc{ timer.continue unless timer.running? }
33  pack(:side=>:left, :fill=>:both, :expand=>true)
34}
35TkButton.new(:text=>'Restart') {
36  command proc{ timer.restart(0, proc{ label.text('0.00'); 0 }) }
37  pack(:side=>:left, :fill=>:both, :expand=>true)
38}
39TkButton.new(:text=>'Stop') {
40  command proc{ timer.stop if timer.running? }
41  pack('side'=>'right','fill'=>'both','expand'=>'yes')
42}
43
44ev_quit = TkVirtualEvent.new('Control-c', 'Control-q')
45Tk.root.bind(ev_quit, proc{Tk.exit}).focus
46
47Tk.mainloop
48