1#!/usr/bin/env ruby 2 3require 'tk' 4 5class Button_clone < TkLabel 6 def initialize(*args) 7 @command = nil 8 9 if args[-1].kind_of?(Hash) 10 keys = _symbolkey2str(args.pop) 11 @command = keys.delete('command') 12 13 keys['highlightthickness'] = 1 unless keys.key?('highlightthickness') 14 keys['padx'] = '3m' unless keys.key?('padx') 15 keys['pady'] = '1m' unless keys.key?('pady') 16 keys['relief'] = 'raised' unless keys.key?('relief') 17 18 args.push(keys) 19 end 20 21 super(*args) 22 23 @press = false 24 25 self.bind('Enter', proc{self.background(self.activebackground)}) 26 self.bind('Leave', proc{ 27 @press = false 28 self.background(self.highlightbackground) 29 self.relief('raised') 30 }) 31 32 self.bind('ButtonPress-1', proc{@press = true; self.relief('sunken')}) 33 self.bind('ButtonRelease-1', proc{ 34 self.relief('raised') 35 @command.call if @press && @command 36 @press = false 37 }) 38 end 39 40 def command(cmd = Proc.new) 41 @command = cmd 42 end 43 44 def invoke 45 if @command 46 @command.call 47 else 48 '' 49 end 50 end 51end 52 53TkLabel.new(:text=><<EOT).pack 54This is a sample of 'event binding'. 55The first button is a normal button widget. 56And the second one is a normal label widget 57but with some bindings like a button widget. 58EOT 59 60lbl = TkLabel.new(:foreground=>'red').pack(:pady=>3) 61 62v = TkVariable.new(0) 63 64TkFrame.new{|f| 65 TkLabel.new(f, :text=>'click count : ').pack(:side=>:left) 66 TkLabel.new(f, :textvariable=>v).pack(:side=>:left) 67}.pack 68 69TkButton.new(:text=>'normal Button widget', 70 :command=>proc{ 71 puts 'button is clicked!!' 72 lbl.text 'button is clicked!!' 73 v.numeric += 1 74 }){ 75 pack(:fill=>:x, :expand=>true) 76} 77 78Button_clone.new(:text=>'Label with Button binding', 79 :command=>proc{ 80 puts 'label is clicked!!' 81 lbl.text 'label is clicked!!' 82 v.numeric += 1 83 }){ 84 pack(:fill=>:x, :expand=>true) 85} 86 87Tk.mainloop 88