ext/tk/sample/tktimer.rb


DEFINITIONS

This source file includes following functions.


   1  #!/usr/local/bin/ruby
   2  # This script generates a counter with start and stop buttons.
   3  
   4  require "tk"
   5  $label = TkLabel.new {
   6    text '0.00'
   7    relief 'raised'
   8    width 10
   9    pack('side'=>'bottom', 'fill'=>'both')
  10  }
  11  
  12  TkButton.new {
  13    text 'Start'
  14    command proc {
  15      if $stopped
  16        $stopped = FALSE
  17        tick
  18      end
  19    }
  20    pack('side'=>'left','fill'=>'both','expand'=>'yes')
  21  }
  22  TkButton.new {
  23    text 'Stop'
  24    command proc{
  25      exit if $stopped
  26      $stopped = TRUE
  27    }
  28    pack('side'=>'right','fill'=>'both','expand'=>'yes')
  29  }
  30  
  31  $seconds=0
  32  $hundredths=0
  33  $stopped=TRUE
  34  
  35  def tick
  36    if $stopped then return end
  37    Tk.after 50, proc{tick}
  38    $hundredths+=5
  39    if $hundredths >= 100
  40      $hundredths=0
  41      $seconds+=1
  42    end
  43    $label.text format("%d.%02d", $seconds, $hundredths)
  44  end
  45  
  46  root = Tk.root
  47  root.bind "Control-c", proc{root.destroy}
  48  root.bind "Control-q", proc{root.destroy}
  49  Tk.root.focus
  50  Tk.mainloop