<ppdoc>
<copyright>
Copyright (c) 2001 by Addison Wesley Longman, Inc. This material may
be distributed only subject to the terms and conditions set forth in
the Open Publication License, v1.0 or later (the latest version is
presently available at http://www.opencontent.org/openpub/).
<p/>
Distribution of substantively modified versions of this document is
prohibited without the explicit permission of the copyright holder.
<p/>
Distribution of the work or derivative of the work in any standard
(paper) book form is prohibited unless prior permission is obtained
from the copyright holder.
</copyright>

<chapter  ref="xref-000001" name="Ruby Tk">
<p/>
The
Ruby Application Archive contains several extensions that
provide Ruby with a graphical user interface (GUI), including
extensions for Tcl/Tk, GTK, OpenGL, and others.
<p/>
The Tk extension is bundled in the main distribution and works on
both Unix and Windows systems.  To use it, you need to have Tk
installed on your system.  Tk is a large system, and entire books have
been written about it, so we won't waste time or resources by delving
too deeply into Tk itself, but instead concentrate on how to access Tk
features from Ruby.  You'll need one of these reference books in order
to use Tk with Ruby effectively.  The binding we use is closest to the
Perl binding, so you probably want to get a copy of
<em>Learning Perl/Tk</em><nbsp/> or <em>Perl/Tk
  Pocket Reference</em><nbsp/>.
<p/>
Tk works along a composition model---that is, you start off by
creating a container widget (such as a <classname>TkFrame</classname> or <classname>TkRoot</classname>) and then
create the widgets that populate it, such as buttons or labels.
When you are ready to start the GUI, you invoke <tt>Tk.mainloop</tt>.  The
Tk engine then takes control of the program, displaying widgets and
calling your code in response to GUI events.
<section>Simple Tk Application</section>
<p/>
A simple Tk application in Ruby might look something like this:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'tk'
  root = TkRoot.new { title "Ex1" }
  TkLabel.new(root) {
    text  'Hello, World!'
    pack  { padx 15 ; pady 15; side 'left' }
  }
  Tk.mainloop
]]></fullcode>
require<nbsp/>'tk'
root<nbsp/>=<nbsp/>TkRoot.new<nbsp/>{<nbsp/>title<nbsp/>"Ex1"<nbsp/>}
TkLabel.new(root)<nbsp/>{
<nbsp/><nbsp/>text<nbsp/><nbsp/>'Hello,<nbsp/>World!'
<nbsp/><nbsp/>pack<nbsp/><nbsp/>{<nbsp/>padx<nbsp/>15<nbsp/>;<nbsp/>pady<nbsp/>15;<nbsp/>side<nbsp/>'left'<nbsp/>}
}
Tk.mainloop
</alltt>
</codefragment>
<p/>
Let's look at the code a little more closely.
After loading in the <tt>tk</tt> extension module, we create a
root-level frame using <tt>TkRoot.new</tt>.  We then make a label widget
as a child of the root frame, setting several options for the
label.  Finally, we pack the root frame and enter the main GUI event loop.
<p/>
It's a good habit to specify the root explicitly, but you could leave it 
out---along with the extra options---and boil this down to a three-liner:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'tk'
  TkLabel.new { text 'Hello, World!' }
  Tk.mainloop
]]></fullcode>
require<nbsp/>'tk'
TkLabel.new<nbsp/>{<nbsp/>text<nbsp/>'Hello,<nbsp/>World!'<nbsp/>}
Tk.mainloop
</alltt>
</codefragment>
<p/>
That's all there is to it!  Armed with one of the Perl/Tk books we
reference at the start of this chapter, you can now produce all the
sophisticated GUIs you need.  But then again, if you'd like to stick
around for some more details, here they come.
<section>Widgets</section>
<p/>
Creating widgets is easy.
Take the name of the widget as given in the
Tk documentation and add a <tt>Tk</tt> to the front of it.  For instance,
the widgets Label, Button, and Entry become the classes <tt>TkLabel</tt>,
<tt>TkButton</tt>, and <tt>TkEntry</tt>.  You create an instance of a widget
using <tt>new</tt>, just as you would any other object.  If you don't
specify a parent for a given widget, it will default to the root-level
frame.  We usually want to specify the parent of a given widget, along
with many other options---color, size, and so on. We also need to be
able to get information back from our widgets while our program is
running by setting up callbacks and sharing data.
<subsection>Setting Widget Options</subsection>
<p/>
If you look at a Tk reference manual (the one written for Perl/Tk, for
example), you'll notice that options for widgets are usually listed
with a hyphen---as a command-line option might be.  In Perl/Tk,
options are passed to a widget in a <classname>Hash</classname>.  You can do that in Ruby
as well, but you can also pass options using a code block; the name
of the option is used as a method name within the block and arguments to
the option appear as arguments to the method call.  Widgets take a
parent as the first argument, followed by an optional hash of options
or the code block of options.  Thus, the following two forms are
equivalent.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  TkLabel.new(parent_widget) {
    text    'Hello, World!'
    pack('padx'  => 5,
         'pady'  => 5,
         'side'  => 'left')
  }
  # or
  TkLabel.new(parent_widget, text => 'Hello, World!').pack(...)
]]></fullcode>
TkLabel.new(parent_widget)<nbsp/>{
<nbsp/><nbsp/>text<nbsp/><nbsp/><nbsp/><nbsp/>'Hello,<nbsp/>World!'
<nbsp/><nbsp/>pack('padx'<nbsp/><nbsp/>=&gt;<nbsp/>5,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>'pady'<nbsp/><nbsp/>=&gt;<nbsp/>5,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>'side'<nbsp/><nbsp/>=&gt;<nbsp/>'left')
}
#<nbsp/>or
TkLabel.new(parent_widget,<nbsp/>text<nbsp/>=&gt;<nbsp/>'Hello,<nbsp/>World!').pack(...)
</alltt>
</codefragment>
<p/>
One small caution when using the code block form: the scope of
variables is not what you think it is. The block is actually evaluated
in the context of the widget's object, not the caller's. This means
that the caller's instance variables will not be available in the
block, but local variables from the enclosing scope and globals (not
that you ever use <em>those</em>) will be.  We'll show option passing
using both methods in the examples that follow.
<p/>
Distances (as in the <tt>padx</tt> and <tt>pady</tt> options in these
examples) are assumed to be in pixels, but may be specified in
different units using one of the suffixes ``<tt>c</tt>'' (centimeter),
``<tt>i</tt>'' (inch), ``<tt>m</tt>'' (millimeter), or ``<tt>p</tt>'' (point).
<subsection>Getting Widget Data</subsection>
<p/>
We can get information back from widgets with callbacks and by 
binding variables.
<p/>
Callbacks are very easy to set up.  The <tt>command</tt> option (shown in
the <tt>TkButton</tt> call in the example that follows) takes a <classname>Proc</classname>
object, which will be called when the callback fires.  Here we use
<mmm><file>kernel</file><front>Kernel</front><back>proc</back><mref>proc</mref></mmm> to convert the <tt>{exit}</tt> block to a <classname>Proc</classname>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  TkButton.new(bottom) {
    text "Ok"
    command proc { p mycheck.value; exit }
    pack('side'=>'left', 'padx'=>10, 'pady'=>10)
  }
]]></fullcode>
TkButton.new(bottom)<nbsp/>{
<nbsp/><nbsp/>text<nbsp/>"Ok"
<nbsp/><nbsp/>command<nbsp/>proc<nbsp/>{<nbsp/>p<nbsp/>mycheck.value;<nbsp/>exit<nbsp/>}
<nbsp/><nbsp/>pack('side'=&gt;'left',<nbsp/>'padx'=&gt;10,<nbsp/>'pady'=&gt;10)
}
</alltt>
</codefragment>
<p/>
We can also bind a Ruby variable to a Tk widget's value using a
<classname>TkVariable</classname> proxy.  We show this in the following example. Notice
how the <classname>TkCheckButton</classname> is set up; the documentation says that the
<tt>variable</tt> option takes a <em>var reference</em> as an argument.  For
this, we create a Tk variable reference using <ccm><front>TkVariable</front><back>new</back></ccm>.
Accessing <tt>mycheck.value</tt> will return the string ``<tt>0</tt>'' or
``<tt>1</tt>'' depending on whether the checkbox is checked.  You can use
the same mechanism for anything that supports a var reference, such as
radio buttons and text fields.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  mycheck = TkVariable.new

  TkCheckButton.new(top) {
    variable mycheck
    pack('padx'=>5, 'pady'=>5, 'side' => 'left')
  }
]]></fullcode>
mycheck<nbsp/>=<nbsp/>TkVariable.new
<p/>
TkCheckButton.new(top)<nbsp/>{
<nbsp/><nbsp/>variable<nbsp/>mycheck
<nbsp/><nbsp/>pack('padx'=&gt;5,<nbsp/>'pady'=&gt;5,<nbsp/>'side'<nbsp/>=&gt;<nbsp/>'left')
}
</alltt>
</codefragment>
<subsection>Setting/Getting Options Dynamically</subsection>
<p/>
In addition to setting a widget's options when it's created, you can
reconfigure a widget while it's running.  Every widget supports the
<tt>configure</tt> method, which takes a <classname>Hash</classname> or a code block in the
same manner as <tt>new</tt>.  We can modify the first example to change
the label text in response to a button press:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  require 'tk'
!-  root = TkRoot.new { title "Ex3" }
!-  top = TkFrame.new(root) { relief 'raised'; border 5 }
  lbl = TkLabel.new(top) { justify 'center' 
    text    'Hello, World!';
    pack('padx'=>5, 'pady'=>5, 'side' => 'top') }
!-  TkButton.new(top) {
!-    text "Ok"; command proc { exit }
!-    pack('side'=>'left', 'padx'=>10, 'pady'=>10)
!-  }
  TkButton.new(top) {
    text "Cancel"
    command proc { lbl.configure('text'=>"Goodbye, Cruel World!") }
    pack('side'=>'right', 'padx'=>10, 'pady'=>10)
  }
!-
!-  top.pack('fill'=>'both', 'side' =>'top')
!-  Tk.mainloop
]]></fullcode>
lbl<nbsp/>=<nbsp/>TkLabel.new(top)<nbsp/>{<nbsp/>justify<nbsp/>'center'
<nbsp/><nbsp/>text<nbsp/><nbsp/><nbsp/><nbsp/>'Hello,<nbsp/>World!';
<nbsp/><nbsp/>pack('padx'=&gt;5,<nbsp/>'pady'=&gt;5,<nbsp/>'side'<nbsp/>=&gt;<nbsp/>'top')<nbsp/>}
TkButton.new(top)<nbsp/>{
<nbsp/><nbsp/>text<nbsp/>"Cancel"
<nbsp/><nbsp/>command<nbsp/>proc<nbsp/>{<nbsp/>lbl.configure('text'=&gt;"Goodbye,<nbsp/>Cruel<nbsp/>World!")<nbsp/>}
<nbsp/><nbsp/>pack('side'=&gt;'right',<nbsp/>'padx'=&gt;10,<nbsp/>'pady'=&gt;10)
}
</alltt>
</codefragment>
<p/>
Now when the <tt>Cancel</tt> button is pressed, the text in the label will
change immediately from ``<tt>Hello, World!</tt>'' to ``<tt>Goodbye, Cruel
  World!</tt>''
<p/>
You can also query widgets for particular option values using
<tt>cget</tt>:
<p/>
<codefragment>
<fullcode><![CDATA[  require 'tk'
  b = TkButton.new {
    text     "OK"
    justify  'left'
    border   5
  }
  b.cget('text')
  b.cget('justify')
  b.cget('border')
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>require<nbsp/>'tk'</tt></td>
</tr>
<tr>
<td colspan="3"><tt>b<nbsp/>=<nbsp/>TkButton.new<nbsp/>{</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>text<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"OK"</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>justify<nbsp/><nbsp/>'left'</tt></td>
</tr>
<tr>
<td colspan="3"><tt><nbsp/><nbsp/>border<nbsp/><nbsp/><nbsp/>5</tt></td>
</tr>
<tr>
<td colspan="3"><tt>}</tt></td>
</tr>
<tr>
  <td><tt>b.cget('text')</tt></td>
  <td>&#187;</td>
  <td><tt>"OK"</tt></td>
</tr>
<tr>
  <td><tt>b.cget('justify')</tt></td>
  <td>&#187;</td>
  <td><tt>"left"</tt></td>
</tr>
<tr>
  <td><tt>b.cget('border')</tt></td>
  <td>&#187;</td>
  <td><tt>5</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<subsection>Sample Application</subsection>
<p/>
Here's a slightly longer example, showing a genuine application---a
``pig Latin'' generator.  
Type in the phrase such as ``Ruby rules,''
and the ``Pig It'' button will instantly translate it into pig Latin.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[require 'tk'

class PigBox
  def pig(word)
    leadingCap = word =~ /^[A-Z]/
    word.downcase!
    res = case word
      when /^[aeiouy]/
        word+"way"
      when /^([^aeiouy]+)(.*)/
        $2+$1+"ay"
      else
        word
    end
    leadingCap ? res.capitalize : res
  end

  def showPig
    @text.value = @text.value.split.collect{|w| pig(w)}.join(" ")
  end

  def initialize
    ph = { 'padx' => 10, 'pady' => 10 }     # common options
    p = proc {showPig}

    @text = TkVariable.new
    root = TkRoot.new { title "Pig" }
    top = TkFrame.new(root)
    TkLabel.new(top) {text    'Enter Text:' ; pack(ph) }
    @entry = TkEntry.new(top, 'textvariable' => @text)
    @entry.pack(ph)
    TkButton.new(top) {text 'Pig It'; command p; pack ph}
    TkButton.new(top) {text 'Exit'; command {proc exit}; pack ph}
    top.pack('fill'=>'both', 'side' =>'top')
  end
end

PigBox.new
Tk.mainloop
]]></fullcode>
require<nbsp/>'tk'
<p/>
class<nbsp/>PigBox
<nbsp/><nbsp/>def<nbsp/>pig(word)
<nbsp/><nbsp/><nbsp/><nbsp/>leadingCap<nbsp/>=<nbsp/>word<nbsp/>=~<nbsp/>/^A-Z/
<nbsp/><nbsp/><nbsp/><nbsp/>word.downcase!
<nbsp/><nbsp/><nbsp/><nbsp/>res<nbsp/>=<nbsp/>case<nbsp/>word
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>when<nbsp/>/^aeiouy/
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>word+"way"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>when<nbsp/>/^([^aeiouy]+)(.*)/
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>$2+$1+"ay"
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>word
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/><nbsp/><nbsp/>leadingCap<nbsp/>?<nbsp/>res.capitalize<nbsp/>:<nbsp/>res
<nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>def<nbsp/>showPig
<nbsp/><nbsp/><nbsp/><nbsp/>@text.value<nbsp/>=<nbsp/>@text.value.split.collect{|w|<nbsp/>pig(w)}.join("<nbsp/>")
<nbsp/><nbsp/>end
<p/>
<nbsp/><nbsp/>def<nbsp/>initialize
<nbsp/><nbsp/><nbsp/><nbsp/>ph<nbsp/>=<nbsp/>{<nbsp/>'padx'<nbsp/>=&gt;<nbsp/>10,<nbsp/>'pady'<nbsp/>=&gt;<nbsp/>10<nbsp/>}<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>common<nbsp/>options
<nbsp/><nbsp/><nbsp/><nbsp/>p<nbsp/>=<nbsp/>proc<nbsp/>{showPig}
<p/>
<nbsp/><nbsp/><nbsp/><nbsp/>@text<nbsp/>=<nbsp/>TkVariable.new
<nbsp/><nbsp/><nbsp/><nbsp/>root<nbsp/>=<nbsp/>TkRoot.new<nbsp/>{<nbsp/>title<nbsp/>"Pig"<nbsp/>}
<nbsp/><nbsp/><nbsp/><nbsp/>top<nbsp/>=<nbsp/>TkFrame.new(root)
<nbsp/><nbsp/><nbsp/><nbsp/>TkLabel.new(top)<nbsp/>{text<nbsp/><nbsp/><nbsp/><nbsp/>'Enter<nbsp/>Text:'<nbsp/>;<nbsp/>pack(ph)<nbsp/>}
<nbsp/><nbsp/><nbsp/><nbsp/>@entry<nbsp/>=<nbsp/>TkEntry.new(top,<nbsp/>'textvariable'<nbsp/>=&gt;<nbsp/>@text)
<nbsp/><nbsp/><nbsp/><nbsp/>@entry.pack(ph)
<nbsp/><nbsp/><nbsp/><nbsp/>TkButton.new(top)<nbsp/>{text<nbsp/>'Pig<nbsp/>It';<nbsp/>command<nbsp/>p;<nbsp/>pack<nbsp/>ph}
<nbsp/><nbsp/><nbsp/><nbsp/>TkButton.new(top)<nbsp/>{text<nbsp/>'Exit';<nbsp/>command<nbsp/>{proc<nbsp/>exit};<nbsp/>pack<nbsp/>ph}
<nbsp/><nbsp/><nbsp/><nbsp/>top.pack('fill'=&gt;'both',<nbsp/>'side'<nbsp/>=&gt;'top')
<nbsp/><nbsp/>end
end
<p/>
PigBox.new
Tk.mainloop
</alltt>
</codefragment>
<sidebar name="Geometry Management">
<p/>
  In the example code in this chapter,    
  you'll see references to the
  widget method <tt>pack</tt>.  That's a very important call, as it
  turns out---leave it off and you'll never see the widget.  <tt>pack</tt>
  is a command that tells the geometry manager to place the widget
  according to constraints that we specify.  Geometry managers
  recognize three commands:
<p/>
<table>
<th>
  <td><b>Command</b></td>
  <td><b>Placement Specification</b></td>
</th>
<tr>
  <td><tt>pack</tt></td>
  <td>Flexible, constraint-based placement</td>
</tr>
<tr>
  <td><tt>place</tt></td>
  <td>Absolute position</td>
</tr>
<tr>
  <td><tt>grid</tt></td>
  <td>Tabular (row/column) position</td>
</tr>
<bottomrule/></table>
<p/>
As <tt>pack</tt> is the most commonly used command, we'll use it
in our examples.
<p/>
</sidebar>
<p/>
<section>Binding Events</section>
<p/>
Our widgets are exposed to the real world; they get clicked on, the
mouse moves over them, the user tabs into them; all these things, and
more, generate <em>events</em> that we can capture.  You can create a
<em>binding</em> from an event on a particular widget to a block of
code, using the widget's <tt>bind</tt> method.
<p/>
For instance, suppose we've created a button widget that displays an image.
We'd like the image to change when the user's mouse is over the
button.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  image1 = TkPhotoImage.new { file "img1.gif" }
  image2 = TkPhotoImage.new { file "img2.gif" }

  b = TkButton.new(@root) {
    image    image1 
    command  proc { doit }
  }

  b.bind("Enter") { b.configure('image'=>image2) }
  b.bind("Leave") { b.configure('image'=>image1) }
]]></fullcode>
image1<nbsp/>=<nbsp/>TkPhotoImage.new<nbsp/>{<nbsp/>file<nbsp/>"img1.gif"<nbsp/>}
image2<nbsp/>=<nbsp/>TkPhotoImage.new<nbsp/>{<nbsp/>file<nbsp/>"img2.gif"<nbsp/>}
<p/>
b<nbsp/>=<nbsp/>TkButton.new(@root)<nbsp/>{
<nbsp/><nbsp/>image<nbsp/><nbsp/><nbsp/><nbsp/>image1
<nbsp/><nbsp/>command<nbsp/><nbsp/>proc<nbsp/>{<nbsp/>doit<nbsp/>}
}
<p/>
b.bind("Enter")<nbsp/>{<nbsp/>b.configure('image'=&gt;image2)<nbsp/>}
b.bind("Leave")<nbsp/>{<nbsp/>b.configure('image'=&gt;image1)<nbsp/>}
</alltt>
</codefragment>
<p/>
First, we create two GIF image objects
from files on disk, using
<tt>TkPhotoImage</tt>.  Next we create a button (very cleverly named
``b''), which displays the image <tt>image1</tt>.  We then bind the
``Enter'' event so that it dynamically changes the image displayed by
the button to <tt>image2</tt>, and the ``Leave'' event to revert back to
<tt>image1</tt>.
<p/>
This example shows the simple events ``Enter'' and ``Leave.''  But the
named event given as an argument to <tt>bind</tt> can be composed of
several substrings, separated with dashes, in the order
<em>modifier-modifier-type-detail</em>.  Modifiers are listed in the Tk
reference and include <tt>Button1</tt>, <tt>Control</tt>, <tt>Alt</tt>,
<tt>Shift</tt>, and so on.  <em>Type</em> is the name of the event (taken
from the X11 naming conventions) and includes events such as
<tt>ButtonPress</tt>, <tt>KeyPress</tt>, and <tt>Expose</tt>.  <em>Detail</em> is
either a number from 1 to 5 for buttons or a keysym for keyboard
input.  For instance, a binding that will trigger on mouse release of
button<nbsp/>1 while the control key is pressed could be specified as:
<p/>
<tt>Control-Button1-ButtonRelease</tt><br/><em>or</em><br/><tt>Control-ButtonRelease-1</tt>
<p/>
The event itself can contain certain fields such as the time of the event
and the x and y positions.  <tt>bind</tt> can pass these items to the callback,
using <em>event field codes</em>.  These are used like <tt>printf</tt>
specifications.  For instance, to get the x and y coordinates on
a mouse move, you'd specify the call to <tt>bind</tt> with three
parameters. The second parameter is the <classname>Proc</classname> for the callback, and 
the third parameter is the event field string.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  canvas.bind("Motion", proc{|x, y| do_motion (x, y)}, "%x %y")
]]></fullcode>
canvas.bind("Motion",<nbsp/>proc{|x,<nbsp/>y|<nbsp/>do_motion<nbsp/>(x,<nbsp/>y)},<nbsp/>"%x<nbsp/>%y")
</alltt>
</codefragment>
<section>Canvas</section>
<p/>
Tk provides a <em>Canvas</em> widget with which you can draw and produce
PostScript output.  Here's a simple bit of code (adapted from the
distribution) that will draw straight lines. Clicking and holding
button<nbsp/>1 will start a line, which will be ``rubber-banded'' as you
move the mouse around.  When you release button<nbsp/>1, the line will be
drawn in that position.  Pressing button<nbsp/>2 on the mouse will dump out
a PostScript representation of the drawing canvas, suitable for
printing.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'tk'
  
  class Draw
    def do_press(x, y)
      @start_x = x
      @start_y = y
      @current_line = TkcLine.new(@canvas, x, y, x, y)
    end
    def do_motion(x, y)
      if @current_line
        @current_line.coords @start_x, @start_y, x, y
      end
    end
    def do_release(x, y)
      if @current_line
        @current_line.coords @start_x, @start_y, x, y
        @current_line.fill 'black'
        @current_line = nil
      end
    end
    def initialize(parent)
      @canvas = TkCanvas.new(parent)
      @canvas.pack
      @start_x = @start_y = 0
      @canvas.bind("1", proc{|e| do_press(e.x, e.y)})
      @canvas.bind("2", proc{ puts @canvas.postscript({}) })
      @canvas.bind("B1-Motion", proc{|x, y| do_motion(x, y)}, "%x %y")
      @canvas.bind("ButtonRelease-1",
                   proc{|x, y| do_release (x, y)}, "%x %y")
    end
  end

  root = TkRoot.new{ title 'Canvas' }
  Draw.new(root)
  Tk.mainloop
]]></fullcode>
require<nbsp/>'tk'
<p/>
class<nbsp/>Draw
<nbsp/><nbsp/>def<nbsp/>do_press(x,<nbsp/>y)
<nbsp/><nbsp/><nbsp/><nbsp/>@start_x<nbsp/>=<nbsp/>x
<nbsp/><nbsp/><nbsp/><nbsp/>@start_y<nbsp/>=<nbsp/>y
<nbsp/><nbsp/><nbsp/><nbsp/>@current_line<nbsp/>=<nbsp/>TkcLine.new(@canvas,<nbsp/>x,<nbsp/>y,<nbsp/>x,<nbsp/>y)
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>do_motion(x,<nbsp/>y)
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>@current_line
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>@current_line.coords<nbsp/>@start_x,<nbsp/>@start_y,<nbsp/>x,<nbsp/>y
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>do_release(x,<nbsp/>y)
<nbsp/><nbsp/><nbsp/><nbsp/>if<nbsp/>@current_line
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>@current_line.coords<nbsp/>@start_x,<nbsp/>@start_y,<nbsp/>x,<nbsp/>y
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>@current_line.fill<nbsp/>'black'
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>@current_line<nbsp/>=<nbsp/>nil
<nbsp/><nbsp/><nbsp/><nbsp/>end
<nbsp/><nbsp/>end
<nbsp/><nbsp/>def<nbsp/>initialize(parent)
<nbsp/><nbsp/><nbsp/><nbsp/>@canvas<nbsp/>=<nbsp/>TkCanvas.new(parent)
<nbsp/><nbsp/><nbsp/><nbsp/>@canvas.pack
<nbsp/><nbsp/><nbsp/><nbsp/>@start_x<nbsp/>=<nbsp/>@start_y<nbsp/>=<nbsp/>0
<nbsp/><nbsp/><nbsp/><nbsp/>@canvas.bind("1",<nbsp/>proc{|e|<nbsp/>do_press(e.x,<nbsp/>e.y)})
<nbsp/><nbsp/><nbsp/><nbsp/>@canvas.bind("2",<nbsp/>proc{<nbsp/>puts<nbsp/>@canvas.postscript({})<nbsp/>})
<nbsp/><nbsp/><nbsp/><nbsp/>@canvas.bind("B1-Motion",<nbsp/>proc{|x,<nbsp/>y|<nbsp/>do_motion(x,<nbsp/>y)},<nbsp/>"%x<nbsp/>%y")
<nbsp/><nbsp/><nbsp/><nbsp/>@canvas.bind("ButtonRelease-1",
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>proc{|x,<nbsp/>y|<nbsp/>do_release<nbsp/>(x,<nbsp/>y)},<nbsp/>"%x<nbsp/>%y")
<nbsp/><nbsp/>end
end
<p/>
root<nbsp/>=<nbsp/>TkRoot.new{<nbsp/>title<nbsp/>'Canvas'<nbsp/>}
Draw.new(root)
Tk.mainloop
</alltt>
</codefragment>
<p/>
A few mouse clicks, and you've got an instant masterpiece:
<p/><em>Missing screenshots/canvas.ps</em><p/>
<p/>
``We couldn't find the artist, so we had to hang the picture....''
<section>Scrolling</section>
<p/>
Unless you plan on drawing very small pictures, the previous example
may not be all that useful.
<classname>TkCanvas</classname>, <classname>TkListbox</classname>, and
<classname>TkText</classname> can be set up to use scrollbars, so you can work on a
smaller subset of the ``big picture.''
<p/>
Communication between a scrollbar and a widget is
bidirectional. Moving the scrollbar means that the widget's view
has to change; but when the widget's view is changed by some other
means, the scrollbar has to change as well to reflect the new
position.
<p/>
Since we haven't done much with lists yet, our scrolling example will
use a scrolling list of text.  In the following code fragment, we'll
start off by creating a plain old <classname>TkListbox</classname>.  Then, we'll make a
<classname>TkScrollbar</classname>.  The scrollbar's callback (set with <tt>command</tt>)
will call the list widget's <tt>yview</tt> method, which will change the
value of the visible portion of the list in the y-direction.
<p/>
After that callback is set up, we make the inverse association: when the list
feels the need to scroll, we'll set the appropriate range in the
scrollbar using <cim><front>TkScrollbar</front><back>set</back></cim>.  
We'll use this same fragment in a fully functional program in the next
section.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-require 'tk'
!-
!-def busy 
!-  begin
!-    $root.cursor "watch" # Set a watch cursor
!-    $root.update # Make sure it updates  the screen
!-    yield # Call the associated block
!-  ensure
!-    $root.cursor "" # Back to original
!-    $root.update
!-  end
!-end
!-
!-$root = TkRoot.new {title 'Scroll List'}
!-frame = TkFrame.new($root)
!-
list_w = TkListbox.new(frame, 'selectmode' => 'single')

scroll_bar = TkScrollbar.new(frame, 
                  'command' => proc { |*args| list_w.yview *args })

scroll_bar.pack('side' => 'left', 'fill' => 'y')

list_w.yscrollcommand(proc { |first,last| 
                             scroll_bar.set(first,last) })
!-list_w.pack('side'=>'left')
!-
!-image_w = TkPhotoImage.new
!-TkLabel.new(frame, 'image' => image_w).pack('side'=>'left')
!-frame.pack
!-
!-list_contents = Dir["screenshots/gifs/*.gif"]
!-list_contents.each {|x|
!-  list_w.insert('end',x) # Insert each file name into the list
!-}
!-list_w.bind("ButtonRelease-1") { 
!-  index = list_w.curselection[0]
!-  busy {
!-    tmp_img = TkPhotoImage.new('file'=> list_contents[index])
!-    scale   = tmp_img.height / 100
!-    scale   = 1 if scale < 1
!-    image_w.copy(tmp_img, 'subsample' => [scale,scale])
!-    tmp_img = nil # Be sure to remove it, the
!-    GC.start      # image may have been large
!-  }
!-}
!-
!-Tk.mainloop
]]></fullcode>
list_w<nbsp/>=<nbsp/>TkListbox.new(frame,<nbsp/>'selectmode'<nbsp/>=&gt;<nbsp/>'single')
<p/>
scroll_bar<nbsp/>=<nbsp/>TkScrollbar.new(frame,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>'command'<nbsp/>=&gt;<nbsp/>proc<nbsp/>{<nbsp/>|*args|<nbsp/>list_w.yview<nbsp/>*args<nbsp/>})
<p/>
scroll_bar.pack('side'<nbsp/>=&gt;<nbsp/>'left',<nbsp/>'fill'<nbsp/>=&gt;<nbsp/>'y')
<p/>
list_w.yscrollcommand(proc<nbsp/>{<nbsp/>|first,last|
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>scroll_bar.set(first,last)<nbsp/>})
</alltt>
</codefragment>
<subsection>Just One More Thing</subsection>
<p/>
We could go on about Tk for another few hundred pages, but that's
another book.  The following program is our final Tk example---a
simple GIF image viewer.  You can select a GIF filename from the
scrolling list, and a thumb nail version of the image will be
displayed.  There are just a <em>few</em> more things we'd like to point
out.
<p/>
Have you ever seen an application that creates a ``busy cursor'' and
then forgets to reset it to normal?  There's a neat trick in 
Ruby that will prevent this from happening.  Remember how
<ccm><file>file</file><front>File</front><back>new</back><mref>new</mref></ccm> uses a block to ensure that the file is closed after it 
is used? We can do a similar thing with the method <tt>busy</tt>, as shown
in the next example.
<p/>
This program also demonstrates some simple <classname>TkListbox</classname>
manipulations---adding elements to the list, setting up a callback on a
mouse button release,<footnote>You probably want the button release,
  not the press, as the widget gets selected on the button press.</footnote> and
retrieving the current selection.
<p/>
So far, we've used <classname>TkPhotoImage</classname> to only display icons directly,
but you can also zoom, subsample, and show portions of images as
well.  Here we use the subsample feature to scale down the image for
viewing.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[require 'tk'

def busy 
  begin
    $root.cursor "watch" # Set a watch cursor
    $root.update # Make sure it updates  the screen
    yield # Call the associated block
  ensure
    $root.cursor "" # Back to original
    $root.update
  end
end

$root = TkRoot.new {title 'Scroll List'}
frame = TkFrame.new($root)

list_w = TkListbox.new(frame, 'selectmode' => 'single')

scroll_bar = TkScrollbar.new(frame, 
                  'command' => proc { |*args| list_w.yview *args })

scroll_bar.pack('side' => 'left', 'fill' => 'y')

list_w.yscrollcommand(proc { |first,last| 
                             scroll_bar.set(first,last) })
list_w.pack('side'=>'left')

image_w = TkPhotoImage.new
TkLabel.new(frame, 'image' => image_w).pack('side'=>'left')
frame.pack

list_contents = Dir["screenshots/gifs/*.gif"]
list_contents.each {|x|
  list_w.insert('end',x) # Insert each file name into the list
}
list_w.bind("ButtonRelease-1") { 
  index = list_w.curselection[0]
  busy {
    tmp_img = TkPhotoImage.new('file'=> list_contents[index])
    scale   = tmp_img.height / 100
    scale   = 1 if scale < 1
    image_w.copy(tmp_img, 'subsample' => [scale,scale])
    tmp_img = nil # Be sure to remove it, the
    GC.start      # image may have been large
  }
}

Tk.mainloop
]]></fullcode>
require<nbsp/>'tk'
<p/>
def<nbsp/>busy
<nbsp/><nbsp/>begin
<nbsp/><nbsp/><nbsp/><nbsp/>$root.cursor<nbsp/>"watch"<nbsp/>#<nbsp/>Set<nbsp/>a<nbsp/>watch<nbsp/>cursor
<nbsp/><nbsp/><nbsp/><nbsp/>$root.update<nbsp/>#<nbsp/>Make<nbsp/>sure<nbsp/>it<nbsp/>updates<nbsp/><nbsp/>the<nbsp/>screen
<nbsp/><nbsp/><nbsp/><nbsp/>yield<nbsp/>#<nbsp/>Call<nbsp/>the<nbsp/>associated<nbsp/>block
<nbsp/><nbsp/>ensure
<nbsp/><nbsp/><nbsp/><nbsp/>$root.cursor<nbsp/>""<nbsp/>#<nbsp/>Back<nbsp/>to<nbsp/>original
<nbsp/><nbsp/><nbsp/><nbsp/>$root.update
<nbsp/><nbsp/>end
end
<p/>
$root<nbsp/>=<nbsp/>TkRoot.new<nbsp/>{title<nbsp/>'Scroll<nbsp/>List'}
frame<nbsp/>=<nbsp/>TkFrame.new($root)
<p/>
list_w<nbsp/>=<nbsp/>TkListbox.new(frame,<nbsp/>'selectmode'<nbsp/>=&gt;<nbsp/>'single')
<p/>
scroll_bar<nbsp/>=<nbsp/>TkScrollbar.new(frame,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>'command'<nbsp/>=&gt;<nbsp/>proc<nbsp/>{<nbsp/>|*args|<nbsp/>list_w.yview<nbsp/>*args<nbsp/>})
<p/>
scroll_bar.pack('side'<nbsp/>=&gt;<nbsp/>'left',<nbsp/>'fill'<nbsp/>=&gt;<nbsp/>'y')
<p/>
list_w.yscrollcommand(proc<nbsp/>{<nbsp/>|first,last|
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>scroll_bar.set(first,last)<nbsp/>})
list_w.pack('side'=&gt;'left')
<p/>
image_w<nbsp/>=<nbsp/>TkPhotoImage.new
TkLabel.new(frame,<nbsp/>'image'<nbsp/>=&gt;<nbsp/>image_w).pack('side'=&gt;'left')
frame.pack
<p/>
list_contents<nbsp/>=<nbsp/>Dir["screenshots/gifs/*.gif"]
list_contents.each<nbsp/>{|x|
<nbsp/><nbsp/>list_w.insert('end',x)<nbsp/>#<nbsp/>Insert<nbsp/>each<nbsp/>file<nbsp/>name<nbsp/>into<nbsp/>the<nbsp/>list
}
list_w.bind("ButtonRelease-1")<nbsp/>{
<nbsp/><nbsp/>index<nbsp/>=<nbsp/>list_w.curselection[0]
<nbsp/><nbsp/>busy<nbsp/>{
<nbsp/><nbsp/><nbsp/><nbsp/>tmp_img<nbsp/>=<nbsp/>TkPhotoImage.new('file'=&gt;<nbsp/>list_contents[index])
<nbsp/><nbsp/><nbsp/><nbsp/>scale<nbsp/><nbsp/><nbsp/>=<nbsp/>tmp_img.height<nbsp/>/<nbsp/>100
<nbsp/><nbsp/><nbsp/><nbsp/>scale<nbsp/><nbsp/><nbsp/>=<nbsp/>1<nbsp/>if<nbsp/>scale<nbsp/>&lt;<nbsp/>1
<nbsp/><nbsp/><nbsp/><nbsp/>image_w.copy(tmp_img,<nbsp/>'subsample'<nbsp/>=&gt;<nbsp/>[scale,scale])
<nbsp/><nbsp/><nbsp/><nbsp/>tmp_img<nbsp/>=<nbsp/>nil<nbsp/>#<nbsp/>Be<nbsp/>sure<nbsp/>to<nbsp/>remove<nbsp/>it,<nbsp/>the
<nbsp/><nbsp/><nbsp/><nbsp/>GC.start<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>#<nbsp/>image<nbsp/>may<nbsp/>have<nbsp/>been<nbsp/>large
<nbsp/><nbsp/>}
}
<p/>
Tk.mainloop
</alltt>
</codefragment>
<p/>
Finally, a word about garbage collection---we happened to have a few
very large GIF files lying about<footnote>They were technical
  documents!  Really!</footnote> while testing this code.  We didn't want to
carry these huge images around in memory any longer then necessary, so 
we set the image reference to <tt>nil</tt> and call the garbage collector 
immediately to remove the trash.
<section>Translating from Perl/Tk Documentation</section>
<p/>
That's it, you're on your own now.
For the most part, you can easily translate the documentation given
for Perl/Tk to Ruby.  But there are a few exceptions; some methods are 
not implemented, and there is undocumented extra functionality.  Until a 
Ruby/Tk book comes out, your best bet is to ask on the newsgroup or
read the source code.
<p/>
But in general, it's pretty easy to see what's going on.  Remember
that options may be given as a hash, or in code block style, and the
scope of the code block is within the <classname>TkWidget</classname> being used, not
your class instance.
<subsection>Object Creation</subsection>
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  Perl/Tk:  $widget = $parent->Widget( [ option => value ] )
  Ruby:     widget = TkWidget.new(parent, option-hash)
            widget = TkWidget.new(parent) { code block }
]]></fullcode>
Perl/Tk:<nbsp/><nbsp/>$widget<nbsp/>=<nbsp/>$parent-&gt;Widget(<nbsp/>[<nbsp/>option<nbsp/>=&gt;<nbsp/>value<nbsp/>]<nbsp/>)
Ruby:<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>widget<nbsp/>=<nbsp/>TkWidget.new(parent,<nbsp/>option-hash)
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>widget<nbsp/>=<nbsp/>TkWidget.new(parent)<nbsp/>{<nbsp/>code<nbsp/>block<nbsp/>}
</alltt>
</codefragment>
<p/>
You may not need to save the returned value of the newly created
widget, but it's there if you do.  Don't forget to pack a widget (or
use one of the other geometry calls), or it won't show up.
<subsection>Options</subsection>
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  Perl/Tk:  -background => color
  Ruby:     'background' => color
            { background color }
]]></fullcode>
Perl/Tk:<nbsp/><nbsp/>-background<nbsp/>=&gt;<nbsp/>color
Ruby:<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>'background'<nbsp/>=&gt;<nbsp/>color
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>{<nbsp/>background<nbsp/>color<nbsp/>}
</alltt>
</codefragment>
<p/>
Remember that the code block scope is different.
<subsection>Variable References</subsection>
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  Perl/Tk:  -textvariable => \$variable
            -textvariable => varRef
  Ruby:     ref = TkVariable.new
            'textvariable' => ref
            { textvariable ref }
]]></fullcode>
Perl/Tk:<nbsp/><nbsp/>-textvariable<nbsp/>=&gt;<nbsp/>\$variable
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>-textvariable<nbsp/>=&gt;<nbsp/>varRef
Ruby:<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>ref<nbsp/>=<nbsp/>TkVariable.new
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>'textvariable'<nbsp/>=&gt;<nbsp/>ref
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>{<nbsp/>textvariable<nbsp/>ref<nbsp/>}
</alltt>
</codefragment>
<p/>
Use <tt>TkVariable</tt> to attach a Ruby variable to a widget's value.
You can then use the <tt>value</tt> accessors in <tt>TkVariable</tt>
(<cim><front>TkVariable</front><back>value</back></cim> and <cim><front>TkVariable</front><back>value=</back></cim>) to 
affect the contents of the widget directly.
</chapter>
</ppdoc>
