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 31b_start = TkButton.new(:text=>'Start', :state=>:disabled) { 32 pack(:side=>:left, :fill=>:both, :expand=>true) 33} 34 35b_stop = TkButton.new(:text=>'Stop', :state=>:normal) { 36 pack('side'=>'left', 'fill'=>'both', 'expand'=>'yes') 37} 38 39b_start.command { 40 timer.continue 41 b_stop.state(:normal) 42 b_start.state(:disabled) 43} 44 45b_stop.command { 46 timer.stop 47 b_start.state(:normal) 48 b_stop.state(:disabled) 49} 50 51TkButton.new(:text=>'Reset', :state=>:normal) { 52 command { timer.reset } 53 pack(:side=>:right, :fill=>:both, :expand=>:yes) 54} 55 56ev_quit = TkVirtualEvent.new('Control-c', 'Control-q') 57Tk.root.bind(ev_quit, proc{Tk.exit}).focus 58 59Tk.mainloop 60