1#!/usr/bin/env ruby
2##
3## buttons.rb
4##
5## demonstrates the simulation of a button array
6##
7## ( based on 'buttons.tcl' included source archive of tktable extension )
8##
9require 'tk'
10require 'tkextlib/tktable'
11
12# create the table
13tab  = TkVariable.new_hash
14rows = 20
15cols = 20
16
17table = Tk::TkTable.new(:rows=>rows + 1, :cols=>cols + 1,
18                        :variable=>tab, :titlerows=>1, :titlecols=>1,
19                        :roworigin=>-1, :colorigin=>-1,
20                        :colwidth=>4, :width=>8, :height=>8,
21                        :cursor=>'top_left_arrow', :borderwidth=>2,
22                        :flashmode=>false, :state=>:disabled)
23
24sx = table.xscrollbar(TkScrollbar.new)
25sy = table.yscrollbar(TkScrollbar.new)
26
27Tk.grid(table, sy, :sticky=>:news)
28Tk.grid(sx, :sticky=>:ew)
29
30Tk.root.grid_columnconfig(0, :weight=>1)
31Tk.root.grid_rowconfig(0, :weight=>1)
32
33# set up tags for the various states of the buttons
34table.tag_configure('OFF', :bg=>'red',    :relief=>:raised)
35table.tag_configure('ON',  :bg=>'green',  :relief=>:sunken)
36table.tag_configure('sel', :bg=>'gray75', :relief=>:flat)
37
38# clean up if mouse leaves the widget
39table.bind('Leave', proc{|w| w.selection_clear_all}, '%W')
40
41# highlight the cell under the mouse
42table.bind('Motion', proc{|w, x, y|
43             Tk.callback_break if w.selection_include?(TkComm._at(x,y))
44             w.selection_clear_all
45             w.selection_set(TkComm._at(x,y))
46             Tk.callback_break
47             ## "break" prevents the call to tkTableCheckBorder
48           }, '%W %x %y')
49
50# mousebutton 1 toggles the value of the cell
51# use of "selection includes" would work here
52table.bind('1', proc{|w, x, y|
53             #rc = w.curselection[0]
54             rc = w.index(TkComm._at(x,y))
55             if tab[rc] == 'ON'
56               tab[rc] = 'OFF'
57               w.tag_cell('OFF', rc)
58             else
59               tab[rc] = 'ON'
60               w.tag_cell('ON', rc)
61             end}, '%W %x %y')
62
63
64# inititialize the array, titles, and celltags
650.step(rows){|i|
66  tab[i,-1] = i
67  0.step(cols){|j|
68    if i == 0
69      tab[-1,j] = j
70    end
71    tab[i,j] = "OFF"
72    table.tag_cell('OFF', "#{i},#{j}")
73  }
74}
75
76Tk.mainloop
77