1#!/usr/bin/env ruby 2# 3# timer -- 4# This script generates a counter with start,stop and reset buttons. 5# 6# Copyright (C) 1998 Takaaki Tateishi (ttate@jaist.ac.jp) 7# last update: Sat Jun 27 12:24:14 JST 1998 8# 9 10require "tk" 11require "thread" 12require "tkafter" 13 14$time = "0.00" 15$m = Mutex.new 16$loop = false 17 18def timer_stop 19 $loop = false 20 $m.lock 21end 22 23def timer_start 24 $loop = true 25 $m.unlock 26end 27 28def timer_reset 29 $time = "0.00" 30 $root.countframe.counter['text'] = $time 31end 32 33def timer_loop 34 if $loop 35 $time = $time.succ 36 $root.countframe.counter['text'] = $time 37 end 38 Tk.after(10,proc{timer_loop}) 39end 40 41 42# 43# thread version 44# 45def timer_loop2 46 while true 47 $m.lock 48 $time = $time.succ 49 $root.countframe.counter['text'] = $time 50 sleep(0.01) 51 $m.unlock 52 end 53end 54 55# 56# TkAfter 57# 58def timer_loop3 59 if $loop 60 $time = $time.succ 61 $root.countframe.counter['text'] = $time 62 end 63end 64 65 66class CountFrame < TkFrame 67 attr_reader :counter 68 69 def initialize(parent=nil,keys=nil) 70 super(parent,keys) 71 @counter = TkLabel.new(self, 72 'text'=>$time, 73 'relief'=>'raised') 74 @counter.pack('fill'=>'both') 75 self 76 end 77end 78 79 80class ButtonFrame < TkFrame 81 def initialize(parent=nil,keys=nil) 82 super(parent,keys) 83=begin 84 @stop = TkButton.new(self, 85 'text'=>'Stop', 86 'command'=>proc{timer_stop}) 87 @start = TkButton.new(self, 88 'text'=>'Start', 89 'command'=>proc{timer_start}) 90=end 91 @stop = TkButton.new(self, :text=>'Stop', :state=>:disabled) 92 @start = TkButton.new(self, :text=>'Start', :state=>:normal) 93 94 @stop.command proc{ 95 timer_stop 96 @start.state(:normal) 97 @stop.state(:disabled) 98 } 99 @start.command proc{ 100 timer_start 101 @stop.state(:normal) 102 @start.state(:disabled) 103 } 104 105 @reset = TkButton.new(self, 106 'text'=>'Reset', 107 'command'=>proc{timer_reset}) 108 for b in [@stop,@start,@reset] 109 b.pack('side'=>'left', 'fill'=>'both', 'expand'=>'yes') 110 end 111 end 112end 113 114 115class Timer < TkRoot 116 attr_reader :countframe 117 118 def initialize(*args) 119 super(*args) 120 @countframe = CountFrame.new(self) 121 @buttonframe = ButtonFrame.new(self) 122 for f in [@buttonframe,@countframe] 123 f.pack('side'=>'top', 'fill'=>'both') 124 end 125 self 126 end 127end 128 129 130$root = Timer.new 131 132#$thread = Thread.start{timer_loop2} 133#timer_loop 134TkAfter.new(10,-1,proc{timer_loop3}).start 135 136Tk.mainloop 137