File: binding_sample.rb

package info (click to toggle)
ruby2.1 2.1.5-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 59,972 kB
  • sloc: ruby: 625,579; ansic: 295,220; xml: 25,445; yacc: 9,155; lisp: 2,433; tcl: 949; makefile: 535; sh: 402; perl: 62; python: 47; awk: 36; asm: 35; sed: 31
file content (87 lines) | stat: -rw-r--r-- 2,118 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env ruby

require 'tk'

class Button_clone < TkLabel
  def initialize(*args)
    @command = nil

    if args[-1].kind_of?(Hash)
      keys = _symbolkey2str(args.pop)
      @command = keys.delete('command')

      keys['highlightthickness'] = 1 unless keys.key?('highlightthickness')
      keys['padx'] = '3m' unless keys.key?('padx')
      keys['pady'] = '1m' unless keys.key?('pady')
      keys['relief'] = 'raised' unless keys.key?('relief')

      args.push(keys)
    end

    super(*args)

    @press = false

    self.bind('Enter', proc{self.background(self.activebackground)})
    self.bind('Leave', proc{
                @press = false
                self.background(self.highlightbackground)
                self.relief('raised')
              })

    self.bind('ButtonPress-1', proc{@press = true; self.relief('sunken')})
    self.bind('ButtonRelease-1', proc{
                self.relief('raised')
                @command.call if @press && @command
                @press = false
              })
  end

  def command(cmd = Proc.new)
    @command = cmd
  end

  def invoke
    if @command
      @command.call
    else
      ''
    end
  end
end

TkLabel.new(:text=><<EOT).pack
This is a sample of 'event binding'.
The first button is a normal button widget.
And the second one is a normal label widget
but with some bindings like a button widget.
EOT

lbl = TkLabel.new(:foreground=>'red').pack(:pady=>3)

v = TkVariable.new(0)

TkFrame.new{|f|
  TkLabel.new(f, :text=>'click count : ').pack(:side=>:left)
  TkLabel.new(f, :textvariable=>v).pack(:side=>:left)
}.pack

TkButton.new(:text=>'normal Button widget',
             :command=>proc{
               puts 'button is clicked!!'
               lbl.text 'button is clicked!!'
               v.numeric += 1
             }){
  pack(:fill=>:x, :expand=>true)
}

Button_clone.new(:text=>'Label with Button binding',
                 :command=>proc{
                   puts 'label is clicked!!'
                   lbl.text 'label is clicked!!'
                   v.numeric += 1
                 }){
  pack(:fill=>:x, :expand=>true)
}

Tk.mainloop