Ruby/Tk Classes and Modules

    This document has been translated from Koji Arai's draft Ruby/Tk document
    (available at http://ns103.net/~arai/ruby/rubytk-20011201.html.gz)

    Nagai Hidetoshi's notes on the original footnotes have been included in italics.

    The translation has the following regrettable features:

      * No attempt was made to fix problems or ambiguities in the original, even 
      obvious ones -- remember the original is a draft.
      * The translation has introduced an unknown but large number of problems and
      ambiguities of its own.
      * Nothing was added or clarified -- all footnotes and comments are from the
      original.
      * No attempt was made to use consistent terms, even when the original did.  
      * No proofreading was done.
      * Jankenpon was used to resolve all doubtful or difficult bits.

    That said, enjoy!

    Benjamin Peterson (http://www.jbrowse.com)

Classes

Modules

Exception Classes

TclTkIp

This is a class for using Tcl/Tk directly.

In Ruby/Tk programming, there is no need to be aware of the existence of this class. For details, see ext/tcltklib/MANUAL.euc

TkCore::INTERP is an instance of this class.

Superclass:

Object

Class Methods:

TclTkIp.new

Creates a Tcl/Tk interpreter object.

Methods:

TclTkIp#_eval(str)

Executes the arbitrary Tcl/Tk script given in str. Returns the result.

TclTkIp#_invoke(cmd, *args)

Executes the arbitrary Tcl/Tk command cmd, passing args as arguments. Returns the result.

TclTkIp#_return_value

Returns 0 if the last call to TclTkIp#_invoke or TclTkIp#_eval executed correctly.

TclTkIp#mainloop

Executes the Tcl/Tk main loop. Same as TclTkLib.mainloop *1

TclTkIp#_toUTF8(str, encodename)
TclTkIp#_fromUTF8(str, encodename)

TkKernel

The superclass of TkObject. The subclass redefines the class method new to take a block.

Superclass:

Object

Class Methods:

TkKernel.new {|obj| ...}

Instantiates the TkKernel object.

If a block is given, the created object will run it as an argument. The context within the block will be such that 'self' is the created object.

In short,

TkKernel.new {|obj| ... }

is equivalent to

object = TkKernel.new
object.instance_eval {|obj| ... }

.

TkKernel.new redefines Class#new, so this property is also seen in subclasses of TkKernel.

TkObject

The superclass of all widgets and ofTkCanvas and TkText.

The subclasses of TkObject contain the following kinds of method:

There is normally no reason to be aware of this distinction in Ruby/Tk programming, but depending on implementation such a case may arise. TkObject#method_missing, TkComposite

You can see the options for a given class at a glance with the following method:

require "tk"
puts TkLabel.new.configinfo.collect {|name,| name}

Superclass:

TkKernel

Included Modules:

Tk

TkTreatFont

TkBindCore

Private Methods:

TkObject#tk_send(cmd、*rest)

Execute cmd on 'self', passing rest as parameters. An implementation of a WidgetCommand.

TkObject#tk_trace_variable(v)

This method simply takes argument v but if v is not a TkVariable object then an ArgumentError exception will be raised. There is an internal type check.

Methods:

TkObject#path

Returns the path of the window. The WidgetCommand's result is applied to this path.

TkObject#epath

Returns the path of the window. The widget arranger TkWindow#pack is applied to this path.

The distinction between path and epath is for the sake of implementing TkComposite. *2

TkObject#to_eval

Returns the representation of self in the Tcl/Tk interpreter. This method is overridden in each object to return:

and more. This method communicates internally with the Tcl/Tk interpreter.

(In this manual, the descriptions of particular to_eval implementations are omitted.)

TkObject#[slot]
TkObject#cget(slot)

Returns the value of Optionsslot.

TkObject#[slot] = value
TkObject#configure(slot, value=None)
TkObject#configure(hash)

Sets the value of Optionsslot to value.

require "tk"
TkLabel.new {
  configure('text', "foobar")
  configure('foreground', "red")
  pack
}
Tk.mainloop

When a hash is passed in, the option that corresponds to each key is set to the given value.

require "tk"
TkLabel.new {
  configure('text' => "foobar", 'foreground' => "red")
  pack
}
Tk.mainloop

TkObject#configure_cmd(slot, value)

Sets option slot to value.value is a Proc object.*3

TkObject#configinfo(slot = nil)

For Optionsslot, returns an array containing each of the 5 elements below:

[Option name, parameter name, class name, default value, actual value]

'Parameter name' is a name which, when set in the Option Database(TkOption), is the same as the option name. 'Class name' here is a name that shows the kind of value (nothing to do with a Ruby class).*4

require "tk"
p TkButton.new.configinfo("foreground")

=> ["foreground", "foreground", "Foreground", "Black", "Black"]

When the argument is omitted, an array of arrays is returned containing the above info for each option.

TkObject#event_generate(context, keys=nil)

Generates event context.

By passing a string known as a "virtual event name" to specify a TkVirtualEvent instance, it is possible to raise a Virtual Event.

For details, please refer to TkCore#event_generate.

TkObject#destroy

If a trace variable is defined, cancels that trace.*5

TkObject#method_missing(id, *args)

Executed when an undefined method is called. (See Object#method_missing)

For the purposes of this method, widget options are treated as methods. The variable id is the id of the called method (or option) and the number of args will be 0 or 1.

When there is 1 argument,

configure id.id2name, args[0]

is run. In other words the method creates Options. In this case, the empty string will be returned.

When there are 0 arguments,

cget id.id2name

is run. In other words, the method refers to Options and returns the value of an option.

Note

In a method implemented by method_missing, you cannot make a call from a subclass using super. Diligence is thus required when inheriting new widget classes from the subclasses of TkObject.

require "tk"

class TkButton2 < TkButton
  def text(val = nil)         # redefine option text
    if val
      super "<#{val}>"        # can't call 'text' on TkButton
    else
      super()                 # can't call 'text' on TkButton
    end
  end
end

TkButton2.new {
  p text "a"
  p text
}

((*error-->*)) -:6:in `text': super: no superclass method `text' (NameError)

Read and set options in the way shown below:

require "tk"

class TkButton2 < TkButton
  def text(val = nil)
    if val
      configure "text", "<#{val}>"        # method_missing :text, val
    else
      cget "text"                 # method_missing :text
    end
  end
end

TkButton2.new {
  p text "a"
  p text
}

=> ""
   "<a>"

Standard Options

Below are the standard Tcl/Tk options at a glance, divided by category. However, not all widgets necessarily support all options.

In the explanations below, only the action taken when 1 argument is supplied is given; however, in all cases if 0 arguments are supplied than the existing value is read. TkObject#method_missing

TkObject#activebackground

Sets the background color for when the widget is Active.

require "tk"
TkButton.new.pack.activebackground "black"
Tk.mainloop

TkObject#activeborderwidth

Sets the border color for when the widget is Active.

TkObject#activeforeground

Sets the foreground color for when the widget is Active.

require "tk"
TkButton.new { text "button" }.pack.activeforeground "red"
Tk.mainloop

TkObject#anchor

Specifies where in the widget text and bitmaps will be positioned. Acceptable values are those below:

TkObject#background
TkObject#bg

Usual background color for the widget.

TkObject#bitmap

Specifies a bitmap. Recently, TkObject#image has been used instead.

TkObject#borderwidth
TkObject#bd

Usual border color for the widget.

TkObject#cursor

Specifies the mouse cursor shape to use.*6

TkObject#disabledforeground

The color to use when the widget is Disabled.

require "tk"
TkButton.new {text "normal";   state text}.pack "fill" => "x"
TkButton.new {text "active";   state text}.pack "fill" => "x"
TkButton.new {text "disabled"; state text}.pack "fill" => "x"
Tk.mainloop

TkObject#exportselection

Specifies, as a boolean, whether the application can share its Selection with other applications. Default is true)。

TkObject#font

Sets text font.*7

TkObject#foreground
TkObject#fg

Sets text (and other foreground) color.

TkObject#highlightbackground

When the widget does not have the Input focus, the color of the frame around the widget.

require "tk"
TkButton.new {highlightbackground "red"; highlightcolor "blue"}.
  pack("padx"=>10,"pady"=>10).focus
TkButton.new {highlightbackground "red"; highlightcolor "blue"}.
  pack("padx"=>10,"pady"=>10)
Tk.mainloop

TkObject#highlightcolor

When the widget does have the Input focus, the color of the frame around the widget.

TkObject#highlightthickness

When the widget does have the Input focus, the thickness of the frame.

require "tk"
TkButton.new {
  highlightbackground "red"
  highlightcolor "blue"
  highlightthickness 10
}.pack("padx"=>10,"pady"=>10).focus
TkButton.new {
  highlightbackground "red"
  highlightcolor "blue"
  highlightthickness 10
}.pack("padx"=>10,"pady"=>10)
Tk.mainloop

TkObject#image

Sets the TkImage.

TkObject#insertbackground

Color of the input cursor.

require "tk"
TkEntry.new {
  insertbackground "red"
  insertwidth 50
  insertborderwidth 10
  insert 0, "foobar"
}.pack.focus
Tk.mainloop

TkObject#insertborderwidth

Specifies the width of the input cursor border. Because the cursor width (set in TkObject#insertwidth) is included, the border width cannot be greater than the cursor width.

TkObject#insertofftime

Together with TkObject#insertontime, sets the cursor's blink speed. This value is the time to spend 'off' in milliseconds.

TkObject#insertontime

Together with TkObject#insertofftime, sets the cursor's blink speed. This value is the time to spend 'on' in milliseconds.

TkObject#insertwidth

Sets the width of the input cursor.TkObject#insertborderwidth

TkObject#jump

A boolean that specifies the behavior of the scrollbar, TkScrollbar. When true, the command associated with the scrollbar is executed every time it moves. When false, the command is executed only when the scroll bar is released.

In the example below, a scroll bar with this value set to true and one with this value set to false control a text input widget (TkEntry) together.

require "tk"

s1 = s2 = nil

e = TkEntry.new {
  xscrollcommand {|arg| s1.set *arg; s2.set *arg}
  insert 0, ("a".."z").to_a.join * 3
}.pack "fill"=>"x"

s1 = TkScrollbar.new {
  jump true
  orient "h"
  command {|arg| e.xview *arg }
}.pack "fill"=>"x"

s2 = TkScrollbar.new {
  jump false
  orient "h"
  command {|arg| e.xview *arg }
}.pack "fill"=>"x"

Tk.mainloop

TkObject#justify

Specifies the text justifying method. Acceptable values are as follows:

###--- TkObject#textvariable

TkObject#troughcolor

Sets the color for concavities.

require "tk"
TkScale.new {
  orient "h"
  troughcolor "red"
  pack "fill"=>"x"
}
TkScrollbar.new {
  orient "h"
  troughcolor "red"
  pack "fill"=>"x"
}
Tk.mainloop

TkObject#underline

Specifies where the text is underlined. This can be used to specify a shortcut key.

require "tk"
TkLabel.new { text "fooBar"; underline 3 }.pack
Tk.mainloop

TkObject#wraplength

For text wrapping, specifies the length of a line. If 0, text cannot be wrapped.

require "tk"
TkLabel.new { text "foobar"; wraplength 20; p wraplength}.pack
Tk.mainloop

###--- TkObject#xscrollcommand

###--- TkObject#yscrollcommand

TkWindow

This is the superclass of all widgets.

Superclass:

TkObject

Extended Modules:

TkBindCore

Class Methods:

TkWindow.new(parent=nil, keys=nil)
TkWindow.new(parent=nil, keys=nil) {|win| ... }

The parent widget will be the widget passed in parent. If parentis omitted, the root widget TkRoot will be the parent.

keys is a hash that specifies the Options . Because the options settable in keys are implemented as methods, both

TkLabel.new(nil, "text"=>"foo").pack

and

label = TkLabel.new
label.text "foo"
label.pack

can be written (pack is not an option).

If a block is given, the created widget will execute the block as an argument. The context within the block will be such that 'self' is the created object.

The example above can also be written thus:

TkLabel.new {
  text "foo"
  pack
}

If a block is used, the parent-child relationship can be clearly expressed visually as below:

require "tk"
TkFrame.new {
  TkLabel.new(self) {
    text "foo"
  }.pack
}.pack
Tk.mainloop

However, since self may change within the block, there is the possibility that the names of instance methods, of Ruby's functions and of local variables may collide. Depending on the actual content, it is also necessary to be careful about legibility.

require "tk"

text = "foo"
p text                # <- This is of course a local variable

TkLabel.new {
  text "bar"
  p text              # <- This is a local variable
  p self.text         # <- This is TkLabel#text
  raise           # <- TkWindow#raise called with no exception
}.pack

Tk.mainloop

Private Methods:

TkWindow#create_self

Creates a widget at the Tcl/Tk level. Called from TkWindow#initialize for initialization.

TkWindow subclasses must override this method to create the relevant widget. In this manual, descriptions of the individual subclasses' create_self methods are omitted.

Usually called in the format

tk_call 'Tcl/Tk command', path

*8

Methods:

TkWindow#pack(keys=nil)

Packs widgets. The packed widgets are arranged according to the behavior specified in keys(a {name=>value...} hash). Returns self.

Tk.pack self, keys

is the same as

TkPack.configure self, keys

See TkPack.

TkWindow#unpack

Releases a widget arranged with 'pack' (so they are no longer visible). Returns self.

TkWindow#grid(keys=nil)

Arranges widgets at the intersections of the grid specified in keys. Returns self.

Tk.grid self, keys

is the same as

TkGrid.configure self, keys

See TkGrid.

TkWindow#ungrid

Releases a widget arranged with 'grid' (so they are no longer visible). Returns self.

TkWindow#place(keys=nil)

Places the widget at the location given in keys. Returns self.

keys is a hash containing the following keys:

TkWindow#unplace
TkWindow#place_forget

Releases a widget arranged with 'place' (so they are no longer visible). Returns self.

TkWindow#place_config(keys)

Repositions a widget arranged with 'place' according to the values specified in keys.*9

TkWindow#place_info

Returns the position information of a widget positioned with 'place' as a hash.

TkWindow#pack_slaves

Returns an array of all the widgets packed within the self widget.

TkWindow#pack_info

Returns the position information of a widget positioned with 'pack' as a hash.

TkWindow#place_slaves

Returns an array of all the widgets arranged with 'place' within the self widget.

TkWindow#focus(force = false)

Sets Input focus to self. If forceis true, then the focus will be obtained even if another application has it. Returns self.

TkWindow#grab(arg = nil)

Performs grab-related operations on the widget. When the widget is grabbed, events are not raised with other widgets.

TkWindow#lower(below=None)

Puts the widget below the below widget. When below is omitted, the widget is put at the bottom. Returns self.

TkWindow#raise(above=None)

Puts the widget above the above widget. When above is omitted, the widget is put at the top. Returns self.

Note

In a context where 'self' is an instance of TkWindow,Kernel#raise cannot be used to raise an exception. In Ruby/Tk programming, it is safer to useKernel#fail to raise an exception.

TkWindow#command(cmd=Proc.new)

Register the Proc object given in the argument as a command.

TkButton.new {
  text "button"
  command { puts "button" }
  pack
}
Tk.mainloop

TkWindow#colormodel(model=None)

(This method cannot be used in Tk versions greater than X.X)*10

Specify whether the Ruby/Tk widget's color model should be color or black and white. Without arguments, returns the widget's color model.

Acceptable values for model are as follows:

Returns self.

TkWindow#destroy

Totally destroys the widget.

TkWindow#wait
TkWindow#wait_visibility

Waits for the widget's visibility to change.

TkWindow#wait_destroy

Waits until TkWindow#destroy destroys the widget.

TkWindow#bindtags(taglist=nil)

Specifies the self widget's Taglist as taglist. The taglist is an array showing the propagation of events. It's elements are:

. When the self widget raises an event, each element in the list is found in order, and the appropriate Event Callback Functions are all executed.

Without arguments, return's the widget's taglist.

By default, the taglist consists of:

require "tk"
b1 = TkButton.new
p b1.bindtags

TkToplevel.new {
  TkButton.new(self) {
    p bindtags
  }
}

=> [#<TkButton: @path=".w0000">, TkButton, #<TkRoot: @path=".">, "all"]
   [#<TkButton: @path=".w0002.w0003">, TkButton, \
    #<TkToplevel: @screen=nil, @path=".w0002", @classname=nil>, "all"]

The following is an example of the definition of a taglist:

require "tk"
b1 = TkButton.new.pack
b1.bindtags [b1, Tk.root, "all"]
p b1.bindtags
Tk.mainloop

=> [#<TkButton: @path=".w0000">, #<TkRoot: @path=".">, "all"]

If the widget class is omitted from the list in this way, then a button will not take on the 'pressed' state even if right-clicked. This is because the Event callback function for this action is registered on the button widget class.

By default, in the "all" tag,

require "tk"
p Tk.bindinfo "all"

=> ["Shift-Key-Tab", "Key-Tab", "Key-F10", "Alt-Key"]

actions for the above key events are defined. Accordingly, it is clear that if the "all" tag is not removed from the tag list, actions for these key presses will be defined on all widgets.

Note

Strings can also be specified as elements in the tag list. However, the 'all' widget path and widget class name are handled specially.

If a widget's path name is given in a tag, the effect is the same as if the widget itself were given. In the same way, giving the widget class name (in the case of TkButton, "Button") is the same as giving the widget class. When specifying tags as strings, care must be taken to avoid name collisions. (In ruby-1.4.4, in tk.rb the class TkBindTag was provided for defining unique tags.)

require "tk"
newtag = TkBindTag.new
TkButton.new {
  bindtags [path, "Button", newtag]
  p bindtags
}

=> [#<TkButton: @path=".w0000">, TkButton, #<TkBindTag: btag00000>]

TkRoot

This class represents the root widget. The root widget is at the top of the Ruby/Tk widget hierarchy

Superclass:

TkWindow

Included Modules:

Tk::Wm

Class Methods:

TkRoot.new

Instantiates the root widget object. Always returns the same object. (Only 1 root widget can exist at once in Ruby/Tk)

Methods:

TkRoot#path

Returns the root widget's path, which must be "." and nothing else.

Standard Options:

TkObject#borderwidth TkObject#bd

TkObject#cursor

TkObject#highlightbackground

TkObject#highlightcolor

TkObject#highlightthickness

TkObject#relief

TkObject#takefocus

Options:

TkRoot#background(color)
TkRoot#bg(color)

### --- TkRoot#class ### --- TkRoot#classname

TkRoot#colormap
TkRoot#container(bool)
TkRoot#height
TkRoot#menu
TkRoot#screen
TkRoot#use
TkRoot#visual
TkRoot#width

TkToplevel

Superclass:

TkWindow

Included Modules:

Tk::Wm

Class Methods:

TkToplevel.new(parent=nil, keys=nil)
TkToplevel.new(parent=nil, screen=nil, classname=nil, keys=nil)

Methods:

TkToplevel#specific_class

Standard Options:

TkObject#borderwidth TkObject#bd

TkObject#cursor

TkObject#highlightbackground

TkObject#highlightcolor

TkObject#highlightthickness

TkObject#relief

TkObject#takefocus

Options:

TkToplevel#background(color)
TkToplevel#bg(color)

### --- TkToplevel#class

TkToplevel#classname
TkToplevel#colormap
TkToplevel#container(bool)
TkToplevel#height
TkToplevel#menu
TkToplevel#screen
TkToplevel#use
TkToplevel#visual
TkToplevel#width

TkFrame

A widget whose only purpose is to position other widgets.

To arrange widgets in a grid with TkWindow#pack, you must use the frame widget.

require "tk"

TkFrame.new {
  TkLabel.new(self, {"text"=>"A"}).pack "side"=>"left"
  TkLabel.new(self, {"text"=>"B"}).pack "side"=>"left"
}.pack
TkFrame.new {
  TkLabel.new(self, {"text"=>"C"}).pack "side"=>"left"
  TkLabel.new(self, {"text"=>"D"}).pack "side"=>"left"
}.pack
Tk.mainloop

Superclass:

TkWindow

Standard Options:

TkObject#borderwidth TkObject#bd

TkObject#cursor

TkObject#highlightbackground

TkObject#highlightcolor

TkObject#highlightthickness

TkObject#relief

TkObject#takefocus

Options:

TkFrame#background(color)
TkFrame#bg(color)

Set the frame's color to color. On TkFrame, this option has a special value, "", meaning no color. *11

### --- TkFrame#class

TkFrame#classname

In Tcl/Tk this option is called class, but since that collides with a Ruby reserved word it is defined as classname*12.

This option can only be specified by being passed to new when the object is created. To find the value, use the instance variable @classname.

TkFrame#colormap

This option can only be specified by being passed to new when the object is created. To find the value, use the instance variable of the same name.

TkFrame#container(bool)

This option can only be specified by being passed to new when the object is created. To find the value, use the instance variable of the same name.

TkFrame#height(h)

h is the height of the frame. If h is 0, the height of the frame depends on the widgets positioned within it.

TkFrame#visual

This option can only be specified by being passed to new when the object is created. To find the value, use the instance variable of the same name.

TkFrame#width(w)

w is the width of the frame. If w is 0, the width of the frame depends on the widgets positioned within it.

TkMenubar

Superclass:

TkFrame

Included Modules:

TkComposite

Class Methods:

TkMenubar.new(parent = nil, spec = nil, options = nil)

Methods:

TkMenubar#add_menu(menu_info)
TkMenubar#[index]

TkLabel

This widget represents a label.

require "tk"
TkLabel.new {
  text "label"
  pack
}
Tk.mainloop

Superclass:

TkWindow

Methods:

TkLabel#textvariable(var)

The TkVariable instance var's content is made into a label. If the value of var changes, the label's contents automatically change as well.

Standard Options:

TkObject#anchor

TkObject#background

TkObject#bitmap

TkObject#borderwidth

TkObject#cursor

TkObject#font

TkObject#foreground

TkObject#highlightbackground

TkObject#highlightcolor

TkObject#highlightthickness

TkObject#image

TkObject#justify

TkObject#padx

TkObject#pady

TkObject#relief

TkObject#takefocus

TkObject#text

### TkObject#textvariable

TkObject#underline

TkObject#wraplength

Options:

TkLabel#height
TkLabel#width

TkButton

require "tk"
TkButton.new {
  text "button"
  command { puts "button" }
  pack
}
Tk.mainloop

Superclass:

TkLabel

Methods:

TkButton#invoke

Executes the command option (A TkWindow#command specified with a Proc object).

This allows you to programmatically execute the same functionality that would be invoked on an actual button press.

TkButton#flash

Makes the button flash.

Standard Options:

TkObject#activebackground

TkObject#activeforeground

TkObject#anchor

TkObject#background

TkObject#bitmap

TkObject#borderwidth

TkObject#cursor

TkObject#disabledforeground

TkObject#font

TkObject#foreground

TkObject#highlightbackground

TkObject#highlightcolor

TkObject#highlightthickness

TkObject#image

TkObject#justify

TkObject#padx

TkObject#pady

TkObject#relief

TkObject#takefocus

TkObject#text

### TkObject#textvariable

TkObject#underline

TkObject#wraplength

Options:

### --- TkButton#command

TkButton#default

This method was implemented in Tk version 8.0

One of the 3 values below must be specified:

TkButton#height

Sets the button's height. If the button contains TkObject#text then the number of lines is set; if it contains an TkObject#image then the pixel size of the image is set. (See distance )

TkButton#state

One of the 3 values below must be specified:

TkButton#width

Sets the button's width. If the button contains TkObject#text then the number of characters is set; if it contains an TkObject#image then the pixel size of the image is set. (See distance )

TkRadioButton

require "tk"
v  = TkVariable.new
c = proc {print v, "\n"}
TkRadioButton.new {text "a"; variable v; value 1; select;   command c; pack}
TkRadioButton.new {text "b"; variable v; value 2; deselect; command c; pack}
TkRadioButton.new {text "c"; variable v; value 3; deselect; command c; pack}
Tk.mainloop

Superclass:

TkButton

Methods:

TkRadioButton#deselect

Puts the radion button into the unchecked state.

TkRadioButton#select

Puts the radio button into the checked state.

TkRadioButton#variable(v)

Links the radio button's state to the TkVariable v. Radio buttons linked to the same TkVariable are in the same group. When the radio button is checked, v takes on the value given in TkRadioButton#value.

TkRadioButton#value(val)

Sets the value that the radio button will have when checked to val.

Standard Options:

TkObject#activebackground

TkObject#activeforeground

TkObject#anchor

TkObject#background

TkObject#bitmap

TkObject#borderwidth

TkObject#cursor

TkObject#disabledforeground

TkObject#font

TkObject#foreground

TkObject#highlightbackground

TkObject#highlightcolor

TkObject#highlightthickness

TkObject#image

TkObject#justify

TkObject#padx

TkObject#pady

TkObject#relief

TkObject#takefocus

TkObject#text

### TkObject#textvariable

TkObject#underline

TkObject#wraplength

Options:

### --- TkRadioButton#command

TkRadioButton#height

See TkButton#height

TkRadioButton#indicatoron
TkRadioButton#selectcolor
TkRadioButton#selectimage
TkRadioButton#state

### --- TkRadioButton#value

### --- TkRadioButton#variable

TkRadioButton#width

TkButton#width参照

TkCheckButton

This class is for CheckButton widgets.

The variable option specifies a variable that will be linked to the widget. The values to which this variable will be set can be changed via TkCheckButton#onvalue and TkCheckButton#offvalue . By default, the ON state has a value of 1 and the OFF state is 0.

require "tk"

v1 = TkVariable.new
v2 = TkVariable.new
v3 = TkVariable.new

c = proc {print v1.value,v2.value,v3.value,"\n"}

TkCheckButton.new {text "a"; variable v1; command c; pack}
TkCheckButton.new {text "b"; variable v2; command c; pack}
TkCheckButton.new {text "c"; variable v3; command c; pack}
Tk.mainloop

Superclass:

TkRadioButton

Methods:

TkCheckButton#toggle

Toggles the check button's ON/OFF state.

Standard Options:

TkObject#activebackground

TkObject#activeforeground

TkObject#anchor

TkObject#background

TkObject#bitmap

TkObject#borderwidth

TkObject#cursor

TkObject#disabledforeground

TkObject#font

TkObject#foreground

TkObject#highlightbackground

TkObject#highlightcolor

TkObject#highlightthickness

TkObject#image

TkObject#justify

TkObject#padx

TkObject#pady

TkObject#relief

TkObject#takefocus

TkObject#text

### TkObject#textvariable

TkObject#underline

TkObject#wraplength

Options:

###--- TkCheckButton#command

TkCheckButton#height

TkButton#height参照

TkCheckButton#indicatoron
TkCheckButton#offvalue

Gives the value for when the check button is unchecked.

TkCheckButton#onvalue

Gives the value for when the check button is checked.

TkCheckButton#selectcolor
TkCheckButton#selectimage
TkCheckButton#state

### --- TkCheckButton#variable

TkCheckButton#width

See TkButton#width

TkEntry

In the explanations of the methods below, location is one of the following:

*25

Please contemplate the different actions of each mode below:

require "tk"

list = TkListbox.new {
  ("a".."z").each {|c| insert 'end', c}
}.pack 'fill'=>'both', 'expand'=>true

mode_var = TkVariable.new("browse")       # default mode

TkLabel.new {
  text "select one of below modes"
}.pack 'fill'=>'x'

%w(single browse multiple extended).each {|mode|
  TkRadioButton.new {
    text mode
    variable mode_var
    value mode
    command {
      list.selectmode mode
    }
  }.pack 'side'=>'left', 'fill'=>'x', 'expand'=>true
}
Tk.mainloop

TkListbox#width

Set the width using a string. If 0 is given, the width will be automatically adjusted so that all strings fit (in this case, the value read will be 0)。

require "tk"
TkListbox.new {
 width 0
 insert "end", "a" * 10
 insert "end", "b"
 insert "end", "c"
 p width
}.pack
Tk.mainloop

If the font is not fixed-width, using the string "0" is the norm.

TkScrollbox

A widget that combines a Tk::Scrollbar with a TkListbox. This class is an example of the usage of the TkComposite module.

Superclass:

TkListbox

Included Modules:

TkComposite

TkText

location

Superclass:

TkTextWin

Included Modules:

TkTreatTextTagFont

Scrollable

Class Methods:

TkText.new(*args)

Methods:

TkText#init_instance_variable
TkText#index(index)
TkText#value
TkText#value= (val)
TkText#_addcmd(cmd)
TkText#_addtag(name, obj)
TkText#tagid2obj(tagid)
TkText#tag_names(index=None)
TkText#mark_names
TkText#window_names
TkText#image_names
TkText#set_insert(index)
TkText#set_current(index)
TkText#insert(index, chars, *tags)
TkText#destroy
TkText#backspace
TkText#compare(idx1, op, idx2)
TkText#debug
TkText#debug=(boolean)
TkText#bbox(index)
TkText#dlineinfo(index)
TkText#yview(*what)
TkText#yview_pickplace(*what)
TkText#xview(*what)
TkText#xview_pickplace(*what)
TkText#tag_add(tag, index1, index2=None)
TkText#tag_bind(tag, seq, cmd=Proc.new, args=nil)
TkText#tag_bind_append(tag, seq, cmd=Proc.new, args=nil)
TkText#tag_bindinfo(tag, context=nil)
TkText#tag_cget(tag, key)
TkText#tag_configure(tag, key, val=None)
TkText#tag_configinfo(tag, key=nil)
TkText#tag_raise(tag, above=None)
TkText#tag_lower(tag, below=None)
TkText#tag_remove(tag, *index)
TkText#tag_ranges(tag)
TkText#tag_nextrange(tag, first, last=None)
TkText#tag_prevrange(tag, first, last=None)
TkText#search_with_length(pat,start,stop=None)
TkText#search(pat,start,stop=None)
TkText#rsearch_with_length(pat,start,stop=None)
TkText#rsearch(pat,start,stop=None)

Standard Options:

TkObject#background

TkObject#borderwidth

TkObject#cursor

TkObject#exportselection

TkObject#font

TkObject#foreground

TkObject#highlightbackground

TkObject#highlightcolor

TkObject#highlightthickness

TkObject#insertbackground

TkObject#insertborderwidth

TkObject#insertofftime

TkObject#insertontime

TkObject#insertwidth

TkObject#padx

TkObject#pady

TkObject#relief

TkObject#selectbackground

TkObject#selectborderwidth

TkObject#selectforeground

TkObject#setgrid

TkObject#takefocus

### TkObject#xscrollcommand

### TkObject#yscrollcommand

Options:

TkText#height
TkText#spacing1
TkText#spacing2
TkText#spacing3
TkText#state
TkText#tabs
TkText#width
TkText#wrap

TkMenu

Also see TkMenubutton

require "tk"

v  = TkVariable.new
v1 = TkVariable.new
v2 = TkVariable.new
v3 = TkVariable.new

menu = TkMenu.new {
  title "menu entries"
  tearoff false
  c = proc { p self.entryconfiginfo "end"}
  add "command", {"label"=>"hoge", "command"=>c}
  add "separator"
  add "checkbutton", {"label"=>"hoge1", "command"=>c, "variable"=>v1, "onvalue"=>1}
  add "checkbutton", {"label"=>"hoge2", "command"=>c, "variable"=>v2}
  add "checkbutton", {"label"=>"hoge3", "command"=>c, "variable"=>v3}
  add "separator"
  add "radiobutton", {"label"=>"hoge1", "command"=>c, "variable"=>v}
  add "radiobutton", {"label"=>"hoge2", "command"=>c, "variable"=>v}
  add "radiobutton", {"label"=>"hoge3", "command"=>c, "variable"=>v}
  20.times {|i| p menutype i}
  activate 0
}

Tk.root.bind('Button-1') {|e| menu.post(e.x_root, e.y_root) }

Tk.mainloop

The location mentioned in the method explanations below is one of the following:

Superclass:

TkWindow

Included Modules:

TkTreatMenuEntryFont

Methods:

TkMenu#activate(index)

Makes the element at the location given in index active.

TkMenu#add(type, keys=nil)

Add one of the kind of item specified by type. type is one of the following:

keys is a hash that contains options for the menu item. The possible options are below:

TkMenu#index(index)

Returns the index number of the element whose location is given in index.

TkMenu#invoke(index)

Execute the item whose location is given in index.

TkMenu#insert(index, type, keys=nil)

Insert an item at the location given in index. type and keys are as in TkMenu#add

TkMenu#delete(index, last=None)

Deletes the item whose location is given in index. If last is specified, items from index to last are deleted.

TkMenu#post(x, y)

Positions self at the given coordinates.

require "tk"
menu = TkMenu.new {
  add 'command', {'label'=>'foo1', 'command'=>proc { puts '1'}}
  add 'command', {'label'=>'foo2', 'command'=>proc { puts '2'}}
  add 'command', {'label'=>'foo3', 'command'=>proc { puts '3'}}
}
Tk.root.bind 'Button-3', proc {|e| menu.post e.x_root, e.y_root }
Tk.root.bind 'Button',   proc {|e| menu.unpost }
Tk.mainloop

*27

TkMenu#postcascade(index)

Position a cascade menu at the location given in index. *28

TkMenu#postcommand(cmd=Proc.new)

When self is repositioned, execute cmd. Called from the TkMenu#post method.

TkMenu#menutype(index)

*29

TkMenu#unpost

Make self no longer have a position -- it will no longer be displayed.

TkMenu#yposition(index)

Returns the position pixels of the item whose location is given in index.

TkMenu#entrycget(index, key)

Return the value of the option given in key, for the item whose location is given in index.

TkMenu#entryconfiure(index, key, val=None)
TkMenu#entryconfiure(index, hash)

Sets the value of option key to val, for the item whose location is given in index.

If a hash is given in the 2nd argument, the keys are treated as option names and the values as option values.

TkMenu#entryconfiginfo(index, key=nil)

Sets the value of option key to val, for the item whose location is given in index.

Standard Options

TkObject#activebackground

TkObject#activeborderwidth

TkObject#activeforeground

TkObject#background

TkObject#borderwidth

TkObject#cursor

TkObject#disabledforeground

TkObject#font

TkObject#foreground

TkObject#relief

TkObject#takefocus

Options

### --- TkMenu#postcommand

TkMenu#selectcolor
TkMenu#tearoff
TkMenu#tearoffcommand
TkMenu#title

### --- TkMenu#type

TkScale

require "tk"

TkScale.new {
  orient "horizontal"
  length 200
  from 1
  to 500
  command {|val|
    p val
  }
  pack
}
Tk.mainloop

Superclass:

TkWindow

Methods:

TkScale#get
TkScale#value

Obtains the value of the scale.

TkScale#set(val)
TkScale#value=(val)

Sets the value of the scale to val.

Standard Options:

TkObject#activebackground

TkObject#background

TkObject#borderwidth

TkObject#cursor

TkObject#font

TkObject#foreground

TkObject#highlightbackground

TkObject#highlightcolor

TkObject#highlightthickness

TkObject#orient

TkObject#relief-troughcolor

TkObject#repeatdelay

TkObject#repeatinterval

TkObject#takefocus

Options:

TkScale#bigincrement
TkScale#command
TkScale#digits

Valid digits

TkScale#from(n)

Set the topmost (leftmost) value to n.

TkScale#label(text)

Set the scale widget's label to text.

TkScale#length(len)

Set the scale widget's length.

TkScale#resolution(n)

Sets the size of the smallest possible increment on the scale. The value of the scale will be a multiple of this.

TkScale#showvalue(bool)

Sets whether to show the value (bool="1") or hide it (bool="0").

TkScale#sliderlength(len)

Set the slider length to len.

TkScale#sliderrelief(s)

Set the form of the slider. The value used is one of the following:

*30

TkScale#state
TkScale#tickinterval(n)

Set the interval between gradations on the scale. If n is 0, no ticks are shown.

TkScale#to(n)

Sets the bottommost (rightmost) value to n.

TkScale#variable(v)

Links the TkVariable object v to the scale.

TkScale#width

TkCanvas

require "tk"

TkCanvas.new {
  xscrollincrement 50
  yscrollincrement 50
  scrollregion [10, 10, 500, 500]
  xscrollbar(TkScrollbar.new).grid 'column'=>0, 'row'=>1, 'sticky'=>'ew'
  yscrollbar(TkScrollbar.new).grid 'column'=>1, 'row'=>0, 'sticky'=>'ns'

  TkcOval.new(self, 40, 40, 240, 340)
  grid 'column'=>0, 'row'=>0, 'sticky'=>'nsew'
}
TkGrid.columnconfigure Tk.root, 0, 'weight'=>100
TkGrid.rowconfigure    Tk.root, 0, 'weight'=>100

Tk.mainloop

In the method explanations below, location is one of the following:

Superclass:

TkWindow

Included Modules:

TkTreatCItemFont

Tk::Scrollable

Private Methods:

TkCanvas#tagid(tag)

Methods:

TkCanvas#addtag(tag, mode, *args)
TkCanvas#addtag_above(tagOrId, target)
TkCanvas#addtag_all(tagOrId)
TkCanvas#addtag_below(tagOrId, target)
TkCanvas#addtag_closest(tagOrId, x, y, halo=None, start=None)
TkCanvas#addtag_enclosed(tagOrId, x1, y1, x2, y2)
TkCanvas#addtag_overlapping(tagOrId, x1, y1, x2, y2)
TkCanvas#addtag_withtag(tagOrId, tag)
TkCanvas#bbox(tagOrId, *tags)
TkCanvas#itembind(tag, context, cmd=Proc.new, args=nil)
TkCanvas#itembind_append(tag, context, cmd=Proc.new, args=nil)
TkCanvas#itembindinfo(tag, context=nil)
TkCanvas#canvasx(x, *args)
TkCanvas#canvasy(y, *args)
TkCanvas#coords(tag, *args)
TkCanvas#dchars(tag, first, last=None)
TkCanvas#delete(*args)
TkCanvas#remove(*args)
TkCanvas#dtag(tag, tag_to_del=None)
TkCanvas#find(mode, *args)

Returns the specified item as an array.

Values of mode:

TkCanvas#find_above(target)

Return the item above the one given in target as an array of elements.

TkCanvas#find_all

Return all items as an array.

require "tk"

x1 = 10
y1 = 10
x2 = 250
y2 = 200
x3 = (x2-x1)/2 + x1
y3 = (y2-y1)/2 + y1
TkCanvas.new {
  TkcArc.new       self, x1, y1, x2, y2, 'width'=>2.0
  TkcBitmap.new    self, x3, y3, 'bitmap'=>'error'
  # TkcImage.new   self, x3, y3, 'image'=>TkImage.new('bitmap'=>'error')
  TkcLine.new      self, x1, y1, x2, y2, 'arrow'=>'both'
  TkcOval.new      self, x1, y1, x2, y2
  TkcPolygon.new   self, x3, y1, x2, y3, x3, y2, x1, y3,
         'fill'=>'', 'outline'=>'black'
  TkcRectangle.new self, x1, y1, x2, y2
  TkcText.new      self, x2+20, y2-20, 'text'=>"foo\nbar"
  TkcWindow.new    self, x2, y2, 'window'=>TkButton.new

# puts find_all

pack
}

Tk.mainloop

=> #<TkcArc:0x4036fd50>
   #<TkcBitmap:0x4036fa08>
   #<TkcLine:0x4036f648>
   #<TkcOval:0x4036f60c>
   #<TkcPolygon:0x4036eec8>
   #<TkcRectangle:0x4036eeb4>
   #<TkcText:0x4036e734>
   #<TkcWindow:0x4036e4b4>

((-how to specify an image?-))

TkCanvas#find_below(target)

Return the item below the one given in target as an array of elements.

TkCanvas#find_closest(x, y, halo=None, start=None)
TkCanvas#find_enclosed(x1, y1, x2, y2)

Return the item inside the given rectangle as an array of elements.

TkCanvas#find_overlapping(x1, y1, x2, y2)

Return the item that best fits the given rectangle as an array of elements. Any item that would be found by find_enclosed will be found by find_overlapping.

TkCanvas#find_withtag(tag)
TkCanvas#itemfocus(tagOrId=nil)
TkCanvas#gettags(tagOrId)
TkCanvas#icursor(tagOrId, index)
TkCanvas#index(tagOrId, index)
TkCanvas#insert(tagOrId, index, string)
TkCanvas#itemcget(tagOrId, option)
TkCanvas#itemconfigure(tagOrId, key, value=None)
TkCanvas#itemconfiginfo(tagOrId, key=nil)
TkCanvas#lower(tag, below=None)
TkCanvas#move(tag, x, y)
TkCanvas#postscript(keys)
TkCanvas#raise(tag, above=None)
TkCanvas#scale(tag, x, y, xs, ys)
TkCanvas#scan_mark(x, y)
TkCanvas#scan_dragto(x, y)
TkCanvas#select(mode, *args)
TkCanvas#select_adjust(tagOrId, index)
TkCanvas#select_clear
TkCanvas#select_from(tagOrId, index)
TkCanvas#select_item
TkCanvas#select_to(tagOrId, index)
TkCanvas#itemtype(tag)
TkCanvas#xview(*index)
TkCanvas#yview(*index)

Standard Options:

TkObject#background

TkObject#borderwidth

TkObject#cursor

TkObject#highlightbackground

TkObject#highlightcolor

TkObject#highlightthickness

TkObject#insertbackground

TkObject#insertborderwidth

TkObject#insertofftime

TkObject#insertontime

TkObject#insertwidth

TkObject#relief

TkObject#selectbackground

TkObject#selectborderwidth

TkObject#selectforeground

TkObject#takefocus

### TkObject#xscrollcommand

### TkObject#yscrollcommand

Options:

TkCanvas#closeenough
TkCanvas#confine
TkCanvas#height
TkCanvas#scrollregion
TkCanvas#width
TkCanvas#xscrollincrement
TkCanvas#yscrollincrement

TkDialog

require "tk"
dialog = TkDialog.new('message'=>"test", 'buttons'=>["b1","b2","b3"])
p dialog.value

Superclass:

TkWindow

Extended Modules:

Tk

Class Methods:

TkDialog.new(keys = nil)

Creates a dialog box object. A top level window is displayed, and queries the user for information based on the values specified in keys.

When the user replies to a dialog box, a dialog object is returned. In this way, using TkDialog#value, it is possible to tell what button was pressed.

Methods:

TkDialog#value

Returns which button was pressed, as a number. Buttons are counted from the left starting at 0.

TkDialog#title

Returns the initial value of the dialog box's title ("DIALOG"). The intention is for this method to be overridden in subclasses.

*31

TkDialog#message

Returns the initial value of the dialog box's message ("MESSAGE"). The intention is for this method to be overridden in subclasses.

TkDialog#message_config

Returns the initial value of the dialog box's message settings (nil). The intention is for this method to be overridden in subclasses.

Please override this method to return a hash.

TkDialog#bitmap

Returns the initial value of the dialog box's bitmap ("info"). The intention is for this method to be overridden in subclasses.

*32

TkDialog#bitmap_config

Returns the initial value of the dialog box's bitmap settings (nil). The intention is for this method to be overridden in subclasses.

TkDialog#default_button

Returns the initial value of the dialog box's default button (0). The intention is for this method to be overridden in subclasses.

TkDialog#buttons

Returns the initial value of the dialog box's buttons. The intention is for this method to be overridden in subclasses.

Please override this method to return an array whose elements consist of the text of each button.

TkDialog#button_configs(num)

Returns the initial value of the dialog box's num-th button settings. The intention is for this method to be overridden in subclasses.

TkWarning

Superclass:

TkDialog

Class Methods:

TkWarning.new(mes)

Methods:

*33

TkWarning#message
TkWarning#title
TkWarning#bitmap
TkWarning#default_button
TkWarning#buttons

TkcItem

Superclass:

TkObject

Included Modules:

TkcTagAccess

Class Methods:

TkcItem.type2class(type)

Returns a class determined by type.

type may be any one of:

TkcItem.id2obj(id)
TkcItem.new(parent, *args)

Methods:

TkcItem#id
TkcItem#delete

TkcArc

Superclass:

TkcItem

Methods:

TkcBitmap

Superclass:

TkcItem

Methods:

TkcImage

Superclass:

TkcItem

Methods:

TkcLine

Superclass:

TkcItem

Methods:

TkcOval

Superclass:

TkcItem

Methods:

TkcPolygon

Superclass:

TkcItem

Methods:

TkcRectangle

Superclass:

TkcItem

Methods:

TkcText

Superclass:

TkcItem

Methods:

TkcWindow

Superclass:

TkcItem

Methods:

TkcTag

Superclass:

TkObject

Included Modules:

TkcTagAccess

Class Methods:

TkcTag.id2obj(id)
TkcTag.new(parent, mode=nil, *args)

Methods:

TkcTag#id
TkcTag#delete
TkcTag#set_to_above(target)
TkcTag#set_to_all
TkcTag#set_to_below(target)
TkcTag#set_to_closest(x, y, halo=None, start=None)
TkcTag#set_to_enclosed(x1, y1, x2, y2)
TkcTag#set_to_overlapping(x1, y1, x2, y2)
TkcTag#set_to_withtag(target)

TkcGroup

Superclass:

TkcTag

Methods:

TkcGroup#include(*tags)
TkcGroup#exclude(*tags)

TkcTagAll

Superclass:

TkcTag

Class Methods:

TkcTagAll.new(parent)

TkcTagCurrent

Superclass:

TkcTag

Class Methods:

TkcTagCurrent.new(parent)

TkImage

Superclass:

TkObject

Included Modules:

Tk

Class Methods:

TkImage.names
TkImage.types
TkImage.new(keys=nil)

Methods:

TkImage#delete
TkImage#height
TkImage#itemtype
TkImage#width

TkBitmapImage

Superclass:

TkImage

Class Methods:

TkBitmapImage.new(*args)

TkPhotoImage

Superclass:

TkImage

Class Methods:

TkPhotoImage.new(*args)

Methods:

TkPhotoImage#blank
TkPhotoImage#cget(option)
TkPhotoImage#copy(source, *opts)
TkPhotoImage#get(x, y)
TkPhotoImage#put(data, *to)
TkPhotoImage#read(file, *opts)
TkPhotoImage#redither
TkPhotoImage#write(file, *opts)

TkTextImage

Superclass:

TkObject

Class Methods:

TkTextImage.new(parent, index, keys)

Methods:

TkTextImage#[slot]
TkTextImage#[slot] = value
TkTextImage#cget(slot)
TkTextImage#configure(slot, value=None)
TkTextImage#image
TkTextImage#image=(value)
TkTextImage#configinfo(slot = nil)

TkTextMark

Superclass:

TkObject

Class Methods:

TkTextMark.new(parent, index)

Methods:

TkTextMark#id
TkTextMark#set(where)
TkTextMark#unset
TkTextMark#gravity
TkTextMark#gravity=(direction)
TkTextMark#next(index)
TkTextMark#previous(index)

TkTextMarkAnchor

Superclass:

TkTextMark

Class Methods:

TkTextMarkAnchor.new(parent, index=nil)

TkTextMarkCurrent

Superclass:

TkTextMark

Class Methods:

TkTextMarkCurrent.new(parent, index=nil)

TkTextMarkInsert

Superclass:

TkTextMark

Class Methods:

TkTextMarkInsert.new(parent, index=nil)

TkTextTag

Superclass:

TkObject

Included Modules:

TkTreatTagFont

Class Methods:

TkTextTag.new(parent, *args)

Methods:

TkTextTag#id
TkTextTag#first
TkTextTag#last
TkTextTag#add(*index)
TkTextTag#remove(*index)
TkTextTag#ranges
TkTextTag#nextrange(first, last=None)
TkTextTag#prevrange(first, last=None)
TkTextTag#[key]
TkTextTag#[key] = val
TkTextTag#cget(key)
TkTextTag#configure(key, val=None)
TkTextTag#configinfo(key=nil)
TkTextTag#bind(seq, cmd=Proc.new, args=nil)
TkTextTag#bind_append(seq, cmd=Proc.new, args=nil)
TkTextTag#bindinfo(context=nil)
TkTextTag#raise(above=None)
TkTextTag#lower(below=None)
TkTextTag#destroy

TkTextTagSel

Superclass:

TkTextTag

Class Methods:

TkTextTagSel.new(parent, keys=nil)

TkTextWindow

Superclass:

TkObject

Class Methods:

TkTextWindow.new(parent, index, keys)

Private Methods:

TkTextWindow#_dump(type, *index)
TkTextWindow#_retrieve_braced_text(str, i)
TkTextWindow#_retrieve_backslashed_text(str, i)

Methods:

TkTextWindow#[slot]
TkTextWindow#[slot] = value
TkTextWindow#cget(slot)
TkTextWindow#configure(slot, value=None)
TkTextWindow#window
TkTextWindow#window=(value)
TkTextWindow#create
TkTextWindow#create=(value)
TkTextWindow#configinfo(slot = nil)
TkTextWindow#dump_all(*index)
TkTextWindow#dump_mark(*index)
TkTextWindow#dump_tag(*index)
TkTextWindow#dump_text(*index)
TkTextWindow#dump_window(*index)

TkVirtualEvent

Superclass:

TkObject

Extended Modules:

Tk

Class Methods:

TkVirtualEvent.getobj(event)
TkVirtualEvent.info
TkVirtualEvent.new(*sequences)

Methods:

TkVirtualEvent#add(*sequences)
TkVirtualEvent#delete(*sequences)
TkVirtualEvent#info

TkVariable

A class for accessing Tcl variables. *34

require "tk"
p TkVariable.new(0).value                     # => "0"
p TkVariable.new(1.2).value                   # => "1.2"
p TkVariable.new(["a", "b"]).value            # => {"0"=>"a", "1"=>"b"}
p TkVariable.new(1=>"a", 2=>"b").value        # => {"1"=>"a", "2"=>"b"}

Superclass:

Object

Included Modules:

Tk

Extended Modules:

TkCore

Class Methods:

TkVariable.callback(args)

Executes the Proc object stored earlier by TkVariable#trace. args are an array like this:

[TkVariable instance, "key", "operation"]

TkVariable.new(val="")

Creates a TkVariable with the value given in val. If val is an Array or Hash, the created object will behave like a Tcl Array.

Methods:

TkVariable#wait

Wait for the value to change.

TkVariable#value

Return the value. If self is a Tcl Array (because Tcl arrays are associative arrays), returns a Hash. Otherwise returns an ordinary string.

TkVariable#value=(val)

Sets the value to val.

TkVariable#[index]

Returns the index-th value. self must be a Tcl Array.

TkVariable#[index] = val

Sets the index-th element to val. self must be a Tcl Array.

TkVariable#to_i

Returns the value as a (Fixnum). (At the moment, TkVariable cannot contain a Bignum value).

TkVariable#to_f

Returns the value as a (Float).

TkVariable#to_s

Returns the value as a (String).

TkVariable#to_a

Returns the value as a (Array).

TkVariable#==(other)

True when the value is the same as other. other may be a TkVariable, String, Integer, Float, or Array.

TkVariable#unset(elem=nil)
TkVariable#remove(elem=nil)

When the value is a Tcl array, deletes the elem-th value.

TkVariable#trace_callback(elem, op)

Executes the Proc object previously stored by TkVariable#trace, passing in self, elem, and op as arguments.

require "tk"

var = TkVariable.new(0)

var.trace "rwu", proc {|arg| puts "callback called with #{arg.inspect}"}
var.trace_callback([], "r")

TkVariable#trace(opts, cmd)

Depending on whether opts contains any of "r", "w", and "u", calls the Proc object cmd when the variable is read, written, or deleted respectively. If the method is called 2 or more times, opts then redefines the cmd to be run.

cmd is called with self, an empty string, and "operation" passed to it as arguments. "Array key" is an empty string if the variable is not an array. "operation" is one of "r", "w", or "u".

require "tk"

var = TkVariable.new(0)

var.trace "rwu", proc {|arg| puts "callback called with #{arg.inspect}"}

p var.value
p var.value = 1
p var.unset

=>callback called with [<TkVariable: v00000>, [], "r"]
  "0"
  callback called with [<TkVariable: v00000>, [], "w"]
  "1"
  callback called with [<TkVariable: v00000>, [], "u"]
  ""

TkVariable#trace_element(elem, opts, cmd)
TkVariable#trace_vinfo
TkVariable#trace_vinfo_for_element(elem)
TkVariable#trace_vdelete(opts, cmd)

Deletes the cmd specified previously by TkVariable#trace If opts do not agree with the original settings given in TkVariable#trace, nothing is done.

TkVariable#trace_vdelete_for_element(elem, opts, cmd)

Constants:

TkVariable::TkVar_CB_TBL

A hash containing callback functions. Used internally.

TkVariable::Tk_VARIABLE_ID

Used internally to allocate variable names at the Tcl level.

Tk_VARIABLE_ID is an array but only element 0 is used. This is all because in Ruby the value of a constant cannot be changed.

TkVarAccess

A class for accessing variables already defined in the Tcl library.*35

p TkCore::INTERP._eval("set tclvar 1")  # => 1
var = TkVarAccess.new("tclvar", 2)
p TkCore::INTERP._eval("set tclvar")    # => 2
var.value = 3
p var.value                             # => 3

Superclass:

TkVariable

Class Methods:

TkVarAccess.new(varname, val=nil)

Create an instance, associated with the Tcl variable varname. If val is specified then the value is also set.

TkComm::Event

A class for showing the status of a raised event. If the third argument to TkBindCore#bind is omitted, an instance of this class is passed as an argument to event callback function.

require "tk"
Tk.root.bind('Enter') {|e| p e.is_a? TkComm::Event}
Tk.mainloop

=> true        # <- Displayed when the mouse cursor enters the window

Note This isn't a serious problem, but Object#type (the method that returns the class of an object) is redefined, so that

require "tk"
Tk.root.bind('Enter') {|e| p e.type}
Tk.mainloop

does not display TkComm::Event.

Superclass:

Object

Methods:

TkComm::Event#serial

%#

TkComm::Event#num

%b

Returns the number of the mouse button that started the event.

Only has meaning for the ButtonPress and ButtonRelease events.

TkComm::Event#focus

%f

Returns a booleon indicating the focus state at the time of the event.

Only has meaning for the Enter and Leave events.

TkComm::Event#height

%h

Only has meaning for the Configure and Expose events.

TkComm::Event#keycode

%k

Returns the keycode that caused the event.

Only has meaning for the KeyPress and KeyRelease events.

TkComm::Event#state

%s

Returns any of the following values, or-ed together:*36

These numbers are the values of the X Window System XEvent structure's state.*37

*38

Has meaning only for the ButtonPress, ButtonRelease, Enter, KeyPress, KeyRelease, Leave, Motion, and Visibility events,

TkComm::Event#time

%t

TkComm::Event#width

%w

Has meaning only for the Configure and Expose evens.

TkComm::Event#x

%x

The X coordinate of the mouse cursor when the event was raised.

TkComm::Event#y

%y

The Y coordinate of the mouse cursor when the event was raised.

TkComm::Event#char

%A

The ASCII character corresponding to the event. (However, if the keys 0-9 are pressed, a Fixnum is returned.)

Has meaning only for the KeyPress and KeyRelease events.

*39

TkComm::Event#send_event

%E

true/false

TkComm::Event#keysym

%K

The key symbol corresponding to the event. Has meaning only for the KeyPress and KeyRelease events.

TkComm::Event#keysym_num

%N

The number of the key symbol corresponding to the event. Has meaning only for the KeyPress and KeyRelease events.

TkComm::Event#type

%T

Returns the type of the event. The number returned corresponds to one of the event types below:

These numbers are the values of the X Window System XEvent structure's type.*40

*41

TkComm::Event#widget

%W

Returns the widget that raised the event.

TkComm::Event#x_root

%X

Returns the X coordinate of the mouse cursor in the root window at the time of the event. Has meaning only for the ButtonPress, ButtonRelease, KeyPress, KeyRelease, and Motion events.

TkComm::Event#y_root

%Y

Returns the Y coordinate of the mouse cursor in the root window at the time of the event. Has meaning only for the ButtonPress, ButtonRelease, KeyPress, KeyRelease, and Motion events.

TkAfter

*42

*43

A class to execute an action after a specified time has elapsed or after the script has become idle.

Below is an example that displays the time three times, at intervals of 5 seconds:

require "tk"

TkAfter.new(5 * 1000, 3, proc { p Time.now.asctime }).start
Tk.mainloop

Digital clock example:

require "tk"

v = TkVariable.new(Time.now.asctime)
TkAfter.new(1 * 1000, -1, proc { v.value = Time.now.asctime }).start

TkLabel.new {
  textvariable v
  pack
}
Tk.mainloop

The digital clock above is no more accurate than xclock -digital -update 1. However, the clock below is a serious clock:

require "tk"

v = TkVariable.new(Time.now.asctime)
Thread.new {
  loop do
    v.value = Time.now.asctime
    sleep 1
  end
}

TkLabel.new {
  textvariable v
  pack
}
Tk.mainloop

Superclass:

Object

Included Modules:

TkCore

Extended Modules:

TkCore

Class Methods:

TkAfter.callback(arg)

arg specifies an ID *44, in accordance with which a callback function will be executed.

TkAfter.info

Returns a TkAfter object that is waiting to execute, as an array.

require "tk"

TkAfter.new(1 * 1000, 1, proc {puts "do callback (ruby/tk)"}).start
p TkAfter.info

Tk.mainloop

=> [#<TkAfter: ...>]
   do callback (ruby/tk)

If there is a callback put in place directly by Tcl/Tk, its TkAfter#after_id will also be included in the array.

*45

require "tk"

TkCore::INTERP._eval "after 1000 {puts {callback executing (tcl/tk)}}"
TkAfter.new(1 * 1000, 1, proc {puts "callback executing (ruby/tk)"}).start
p TkAfter.info
Thread.new {
  sleep 5
  p TkAfter.info
}

Tk.mainloop

=> [#<TkAfter: ... >, "after#1"]
   callback executing (tcl/tk)
   callback executing (ruby/tk)
   []

TkAfter.new(interval=nil, loop_exec=nil, *procs])

Creates a TkAfter object. When arguments are given, TkAfter#set_procs is called with those very arguments.

Methods:

TkAfter#do_callback(*args)

A callback function is passed in the args argument, and executed.

TkAfter#set_callback(sleep, args=nil)

Registers a callback function.

TkAfter#set_next_callback(*args)
TkAfter#after_id

Returns a string that identifies a TkAfter callback (The return value of the Tcl/Tk command after).

TkAfter#after_script

Returns the callback function. It's a Tcl script.

TkAfter#current_proc

Returns a Proc object waiting to be executed.

TkAfter#current_sleep

Returns the time to wait before executing (not the amount of time currently remaining).

TkAfter#loop_exec
TkAfter#loop_exec = val
TkAfter#get_procs
TkAfter#current_status

Returns the state of the callback function as an array. In order, the array elements are:

TkAfter#running?

Returns false if the timer is not running or if the given number of repeats has occurred. Otherwise returns true.

TkAfter#loop_rest

Returns the number of times the callback function still has to be executed.

TkAfter#loop_rest=(rest)

Sets the number of times the callback still has to be executed to rest.

TkAfter#set_procs(interval, loop_exec, *procs)

At frequency interval, loop_exec times, execute the Proc objects given in procs. Multiple Proc objects may be given.

interval is a Proc that returns "idle" or a number. The number is the number of milliseconds between invocations of the callback function.

loop_exec specifies the number of times to execute procs as as number. If -1 is given, it will loop forever.

If loop_exec > 0, execution will be done only the specified number of times. After that number of executions, the instance method TkAfter#running? will start to return false.

TkAfter#add_procs(*procs)

procs are added to the callback functions. procs is a Proc object(s) or ??? *46.

TkAfter#set_start_proc(sleep, init_proc, *init_args)

The sleep argument is a number (of milliseconds) or the string "idle".

TkAfter#start(*init_args)

Schedules the callback function to be run with init_args as arguments.

The meanings of the arguments are, respectively:

TkAfter#restart(*restart_args)

Re-run the callback function.

TkAfter#cancel
TkAfter#stop

Suspend the scheduling of the callback function.

TkAfter#continue(wait=nil)

Reactivate a suspended callback. The wait argument can be used to re-specify the wait interval.

TkAfter#skip

Skip one execution of the callback.

TkAfter#info

Returns an array of format: [ID, timer_type]

ID is not the ID returned by TkAfter#after_id, but the identifier used internally in TkAfter*47.

The 'timer_type' must be one of the following:

Constants:

TkAfter::Tk_CBID

A counter for callback IDs. Tk_CBID is an array but only the 0th element is used. This is because it is not possible to change the values of Ruby constants.

TkAfter::Tk_CBTBL

A hash of the form {ID_of_callback => TkAfter object}.

TkFont

-foundry-family-weight-slant-set_width-style-pixels-

points-x_res-y_res-spacing-width-registry-encoding


Included Modules:

Tk

Extended Modules:

TkCore

Class Methods:

TkFont.new(ltn=nil, knj=nil, keys=nil)
TkFont.families(window=nil)

Returns an array giving an overview of font families. *48

TkFont.names

Returns an array giving an overview of font names. TkFont.create_copy(font)

TkFont.get_obj(name)
TkFont.init_widget_font(path, *args)
TkFont.used_on(path=nil)

*49

TkFont#create_asciifont(font)
TkFont#create_latinfont(font)
TkFont#create_kanjifont(font)
TkFont#create_compoundfont(keys)
TkFont#actual_core(font, window=nil, option=nil)
TkFont#configinfo_core(font, option=nil)
TkFont#configure_core(font, slot, value=None)
TkFont#delete_core
TkFont#latin_replace_core(ltn)
TkFont#kanji_replace_core(knj)
TkFont#measure_core(window, text)
TkFont#metrics_core(font, window, option=nil)

Methods:

TkFont#call_font_configure(path, *args)
TkFont#used
TkFont#id
TkFont#font
TkFont#ascii_font
TkFont#latin_font
TkFont#kanji_font
TkFont#actual(option=nil)
TkFont#actual_displayof(window, option=nil)
TkFont#ascii_actual(option=nil)
TkFont#latin_actual(option=nil)
TkFont#ascii_actual_displayof(window, option=nil)
TkFont#latin_actual_displayof(window, option=nil)
TkFont#kanji_actual(option=nil)
TkFont#kanji_actual_displayof(window, option=nil)
TkFont#[slot]
TkFont#[slot] = val
TkFont#configure(slot, value=None)
TkFont#configinfo(slot=nil)
TkFont#delete
TkFont#ascii_configure(slot, value=None)
TkFont#latin_configure(slot, value=None)
TkFont#ascii_configinfo(slot=nil)
TkFont#latin_configinfo(slot=nil)
TkFont#kanji_configure(slot, value=None)
TkFont#kanji_configinfo(slot=nil)
TkFont#replace(ltn, knj)
TkFont#ascii_replace(ltn)
TkFont#latin_replace(ltn)
TkFont#kanji_replace(knj)
TkFont#measure(text)
TkFont#measure_displayof(window, text)
TkFont#metrics(option=nil)
TkFont#metrics_displayof(window, option=nil)
TkFont#ascii_metrics(option=nil)
TkFont#latin_metrics(option=nil)
TkFont#latin_metrics_displayof(window, option=nil)
TkFont#kanji_metrics(option=nil)
TkFont#kanji_metrics_displayof(window, option=nil)
TkFont#reset_pointadjust

Constants

TkFont::Tk_FontID
TkFont::Tk_FontNameTBL
TkFont::Tk_FontUseTBL
TkFont::DEFAULT_LATIN_FONT_NAME
TkFont::DEFAULT_KANJI_FONT_NAME

TkBindTag

Objects of this class can be added to a taglist in order to register an event callback function that is shared among an arbitrary group. Please see TkWindow#bindtags

require "tk"

tag = TkBindTag.new
tag.bind('Return') {|e| p e.widget }

TkButton.new {text 'A'; bindtags bindtags.unshift tag}.pack.focus
TkButton.new {text 'B'; bindtags bindtags.unshift tag}.pack
TkButton.new {text 'C'}.pack
Tk.mainloop

In the above example, buttons A and B have a callback for the Return key, but button C does not.

Superclass:

Object

Included Modules:

TkBindCore

Class Methods:

TkBindTag.id2obj(id)

Returns the instance of TkBindTag matching the string in id. Used internally.

TkBindTag.new
TkBindTag.new(context, cmd=Proc.new, args=nil)

Creates a new tag object for registering a callback function.

By giving arguments, you can create the object and specify the callback function at the same time. The meanings of the arguments are the same as for TkBindCore#bind. Accordingly,

tag = TkBindTag.new
tag.bind('Return') {|e| p e.widget }

can be written as

tag = TkBindTag.new('Return', proc {|e| p e.widget })

.*50

TclTkLib

A module for directly handling Tcl/Tk.

In Ruby/Tk programming there is no reason to be aware of the existence of this class.See ext/tcltklib/MANUAL.euc for details.

Module Functions

TclTkLib.mainloop

Run the main Tcl/Tk main loop. In Ruby/Tk the normal situation is for Tk.mainloop (actually, TkCore#mainloop) to invoke this method in a loop.

TkBindCore

Methods:

TkBindCore#bind(context, cmd=Proc.new, args=nil)

Registers cmd with the event given in context. If args is omitted, then when cmd is run an instance of the event class TkComm::Event is passed. By supplying args, it is possible to limit the information passed to just the keycode and suchlike.

context is any of the following:

When such a combination is specified as an array or (if specified in TkVirtualEvent) a comma-delimited string, a callback can be specified for the resulting chain of events. (This sort of event is called an event sequence).

For instance, ["Escape", "a"] and "Escape,a" both mean a press on the ESC key followed by one on the a key.

require "tk"
Tk.root.bind(['Escape','Key'], proc {|e| p e.keysym})
p Tk.root.bindinfo
Tk.mainloop

=> ["Key-Escape,Key"] # <- event sequence declaration in bindinfo
   "a"            # <- Displayed when ESC is pressed followed by a

In the

"KeyPress" and "ButtonPress" events, "-keycode*51" and "-mouse button number" can be added.

bind "Key-comma", proc {|e| p e}
bind "ButtonPress-1", proc {|e| p e}

Further, the prefixes below can be added to the event string:

For instance, SHIFT+META+"," is as below.

bind "Shift-Meta-Key-comma", proc {|e| p e}

A drag done with mouse button 1 is as below.

bind "B1-Motion", proc {|e| p e}

args consists of the strings below, separated with whitespace.

Example of displaying the mouse location when there is a click on button 1:

require "tk"
Tk.root.bind("1", proc {|x, y| p [x, y]}, "%X %Y")
Tk.mainloop

Of course, the same thing can be done even without specifying args: TkComm::Event

require "tk"
Tk.root.bind("1", proc {|e| p [e.x_root, e.y_root]})
Tk.mainloop

TkBindCore#bind_append(context, cmd=Proc.new, args=nil)

The same as TkBindCore#bind, but if another callback is already registered on the same context, cmd is added to it.

The order in which callbacks are called is the order in which they were registered (Please see TkWindow#bindtags for more information on callback calling order).

TkBindCore#bindinfo(context=nil)

Returns information about the callbacks bound to event context as an array. The elements of this array are the array in the second and third arguments to TkBindCore#bind .

require "tk"
cursor_pos1 = proc {|x,y| printf("X=%d Y=%d\n", x, y)}
cursor_pos2 = proc {|x,y| printf("x=%d y=%d\n", x, y)}
Tk.root.bind       ('Button-1', cursor_pos1, "%X %Y")
Tk.root.bind_append('Button-1', cursor_pos2, "%x %y")
p Tk.root.bindinfo('Button-1')

=> [[#<Proc:0x401354e8>, "%X %Y"], [#<Proc:0x40132ef0>, "%x %y"]]

If context is omitted, returns the types of callback bound to the event as an array.

require "tk"
cursor_pos = proc {|x,y| printf("X=%d Y=%d\n", x, y)}
Tk.root.bind('Button-1', cursor_pos, "%X %Y")
Tk.root.bind('Button-2', cursor_pos, "%X %Y")
p Tk.root.bindinfo

=> ["Button-2", "Button-1"]

TkBgError

A module for error output.

require "tk"

TkButton.new {
  command { TkBgError.show("error!") }
  pack
}
Tk.mainloop

*52

Extended Modules:

Tk

Module Methods:

TkBgError.bgerror(message)
TkBgError.tkerror(message)
TkBgError.show(message)

Displays a dialog containing an error.

In the dialog, there are three buttons.

TkComm

A module for transferring data between Ruby and Tcl/Tk.

The instance methods of this module are, in normal Ruby/Tk programming, used in the form of module methods of Tk.

Private Methods:

TkComm#error_at
TkComm#tk_tcl2ruby(val)

Convert val to a Ruby object.

TkComm#tk_split_list(str)

Return a Tcl list, converting it to an array. The array elements are objects converted as in TkComm#tk_tcl2ruby.

TkComm#tk_split_simplelist(str)

Return a Tcl list, converting it to an array of strings.

TkComm#hash_kv(keys)

Returns the hash ({"key"=>"val", ...}) that is passed in as an array (["-key", "val", ...]).

This is used internally in the Tcl/Tk widget command configure.

TkComm#array2tk_list(ary)

Converts the Ruby array ary to a Tcl list.

TkComm#bool(val)

Returns the Tcl boolean val as a Ruby boolean truby/false.

The Tcl 'true' values "1", 1, "yes", and "true" are returned as true. Everything else is returned as false.

TkComm#number(val)

The Tcl numeric value val(in string form) is returned as a Ruby numeric. If it can't be interpreted as a number, val is returned unchanged.*54

TkComm#string(val)

Returns a Tcl string as a Ruby string. In particular, if val is surrounded in braces "{" "}", they are removed.

TkComm#list(val)

Same as the below.

tk_split_list(((|val|))).to_a

In other words, if val is a one-element Tcl list, it will always be returned as an array.

TkComm#window(val)

Returns the widget matching the Tk widget path widget pathval.

TkComm#procedure(val)

Depending on what has been specified in TkComm#install_cmdi, the Proc matching Tcl Procedure val is returned.

TkComm#_get_eval_string(obj)

Returns the representation of object obj in the Tcl/Tk interpreter.

TkCore#tk_call converts all its arguments using this method before passing them to Tcl.

TkComm#install_cmd(cmd)

Proc object cmd is registered as a procedure. Returns a Tcl script that runs the procedure. *55

TkComm#uninstall_cmd(id)

Deletes the procedure that is registered as id.

TkComm#install_bind(cmd, args=nil)

Returns the Proc object cmd as an event callback function. Returns a Tcl script that runs the procedure.

TkComm#tk_event_sequence(context)

Returns the event identifier context as a string that can be interpreted by Tcl.

require "tk"
p Tk.module_eval { tk_event_sequence ["Escape", "a"] }

=> "Escape><a"

TkComm#_bind_core(mode, path, context, cmd, args=nil)

The implementation of TkComm#_bind and TkComm#_bindappend.

TkComm#_bind(what, context, cmd, args=nil)

The implementation of TkComm#bind.

TkComm#_bind_append(path, context, cmd, args=nil)

The implementation of TkComm#bindappend.

TkComm#_bindinfo(what, context=nil)

The implementation of TkComm#bindinfo.

Methods:

TkComm#_genobj_for_tkwidget(path)

Create a widget object from widget path path. In path, a path generated by the Tcl/Tk library should be given.

This method defines the class of a generated object as KlassGeneratedOnTk. (Where the "Klass" bit is actually a widget class name.)

To convert a Ruby/Tk generated path into an object, use not this method but TkComm#window.

*56

TkComm#_curr_cmd_id

Returns the ID of the next Procedure.

*57

TkComm#_next_cmd_id

Returns the ID of the next Procedure. IDs increase as they are allocated among procedures.

*58

TkComm#install_win(ppath)

Register self as a new child window of the parent window whose path is ppath.

*59

TkComm#uninstall_win

Delete the registered self.

*60

TkComm#bind(tagOrClass, context, cmd=Proc.new, args=nil)

Register a callback function with tagOrClass (Please see TkBindCore#bind for details).

tagOrClass is a tag (TkBindTag), widget, or widget class.

TkComm#bind_append(tagOrClass, context, cmd=Proc.new, args=nil)

Register an additional callback function with tagOrClass (Please see TkBindCore#bind for details).

tagOrClass is a tag (TkBindTag), widget, or widget class.

TkComm#bindinfo(tagOrClass, context=nil)

Return information about an event callback registered with tagOrClass as an array.

tagOrClass is a tag (TkBindTag), widget, or widget class.

require "tk"
Tk.bind_all('Button-1', proc {|x,y| printf("X=%d Y=%d\n", x, y)}, "%X %Y")
Tk.bind_append_all('Button-1',
                        proc {|x,y| printf("x=%d y=%d\n", x, y)}, "%x %y")
p Tk.bindinfo('all', 'Button-1')

=> [[#<Proc:0x4013463c>, "%X %Y"], [#<Proc:0x4013201c>, "%x %y"]]

TkComm#bind_all(context, cmd=Proc.new, args=nil)

Register the callback function cmd (executed when the event specified in context is raised) with all the widgets. For details of context and args, please see TkBindCore#bind and TkComm::Event.

The example below displays the position of the mouse cursor when the mouse is left-clicked.

require "tk"
Tk.bind_all('Button-1', proc {|x,y| printf("X=%d Y=%d\n", x, y)}, "%X %Y")
Tk.mainloop

TkComm#bind_append_all(context, cmd=Proc.new, args=nil)

The same as TkComm#bind_all, but if another callback function is already bound to the same context, cmd is added to it.

The order of execution of callback functions is the same as that in which they were registered. (On the order of execution of callback functions, please see TkWindow#bindtags).

The example below displays the position of the mouse cursor when the mouse is left-clicked. First the location relative to the root window is shown, then the location relative to the widget.

require "tk"
Tk.bind_all('Button-1', proc {|x,y| printf("X=%d Y=%d\n", x, y)}, "%X %Y")
Tk.bind_append_all('Button-1',
                        proc {|x,y| printf("x=%d y=%d\n", x, y)}, "%x %y")
Tk.mainloop

TkComm#bindinfo_all(context=nil)

Returns information about the callback bound to event context as an array. The elements of the returned array are like arguments 2 and 3 of TkComm#bind_all .

require "tk"
cursor_pos1 = proc {|x,y| printf("X=%d Y=%d\n", x, y)}
cursor_pos2 = proc {|x,y| printf("x=%d y=%d\n", x, y)}
Tk.bind_all       ('Button-1', cursor_pos1, "%X %Y")
Tk.bind_append_all('Button-1', cursor_pos2, "%x %y")
p Tk.bindinfo_all('Button-1')

=> [[#<Proc:0x40133bd4>, "%X %Y"], [#<Proc:0x40131618>, "%x %y"]]

If context is omitted, returns the type of the event to which the callback is bound, in an array.

require "tk"
cursor_pos = proc {|x,y| printf("X=%d Y=%d\n", x, y)}
Tk.bind_all('Button-1', cursor_pos, "%X %Y")
Tk.bind_all('Button-2', cursor_pos, "%X %Y")
p Tk.bindinfo_all

=> ["Button-2", "Button-1", "Shift-Key-Tab", "Key-Tab", "Key-F10", "Alt-Key"]

TkComm#pack(*args)

Same as TkPack.configure.

TkComm#grid(*args)

Same as TkGrid.configure.

TkComm#update(idle=nil)

If idle is true, the drawing (etc) of the widget, which is normally not done until the state of Tk becomes idle, is done right away. If idle is false or nil, the accumulated events are all executed.

Constants:

TkComm::WidgetClassNames

A hash storing the actual widget classes keyed by the Tcl/Tk widget class name.

TkComm::None

An object representing a null value. This object is never passed to the Tcl interpreter. (nil is sometimes passed to the Tcl interpreter as an empty string.)

By defining a method thus:

method(arg1, arg2=None)

a both the form method(arg1) and in the form method(arg1, arg2) can be used with just one method.

TkComm::Tk_CMDTBL

A hash: {ProcedureID => Proc Object}

TkComm::Tk_WINDOWS

A hash: {widget path => Window Object}

TkComm::Tk_IDs

An array: [ProcedureID Counter, WindowID counter]

TkCore

In Ruby/Tk programming, this module's instance methods are used in the form of the Tk module's module methods.

Included Modules:

TkComm

Extended Modules:

TkComm

Class Methods:

TkCore.callback(arg)

Methods:

TkCore#callback_break

Raises the TkCallbackBreak exception.

TkCore#callback_continue

Raises the TkCallbackContinue exception.

TkCore#after(ms, cmd=Proc.new)

After ms milliseconds, executes callback function cmd. If ms is the string "idle", cmd will be executed when the status of the script is idle or waiting for input.

If you want to execute the function multiple times, or specify a complicated timer operation, please use TkAfter.

TkCore#appname(name=None)

Sets the application name to name. An application name beginning with a capital letter is forbidden*61.

Called with no arguments, returns the application name.

The application name is used in TkCore#appsend.

Application names are adjusted so as to always be unique. If the given application name already exists, a serial number of the form " #N" will be appended to it.

"tk" is the default application name.

TkCore#appsend(interp, async, *args)
TkCore#rb_appsend(interp, async, *args)
TkCore#appsend_displayof(interp, async, *args)
TkCore#rb_appsend_displayof(interp, async, *args)
TkCore#info(*args)

Returns internal information about the Tcl interpreter.

The first argument specifies the type of information. It is one of the strings below. The remaining arguments vary depending on the first argument. (For details, please see info(n))

TkCore#mainloop

Runs the main loop of Ruby/TK. Polling events and running callback functions is all done from inside this method. Thus, the last thing a Ruby/Tk script does is call this method.

TkCore#event_generate(window, context, keys=nil)

Raise event context in window.

require "tk"
b = TkButton.new {
  text "button1"
  command { puts "push!" }
  focus
}.pack
TkButton.new {
  text "button2"
  command {
    Tk.event_generate(b, "Key-space")
  }
}.pack

Tk.mainloop

If context is a "<virtual event name>" string specifying a TkVirtualEvent instance, a virtual event can be raised.

The optional argument keys is a hash table with the keys below:

TkCore#messageBox(keys)

The argument keys is a hash table with the keys below:

TkCore#getOpenFile(keys)
TkCore#getSaveFile(keys)

A file dialog box for loading/saving.

The argument keys is a hash table with the keys below:

Returns the chosen file name. If the file choosing operation is cancelled, returns the empty string "".

TkCore#chooseColor(keys)

A dialog box for choosing a color.

The argument keys is a hash table with the keys below:

The chosen color is returned as a string in "#RRGGBB" format. If the color choosing operation is cancelled, returns the empty string "".

TkCore#tk_call(*args)

args is turned into a Tcl string with TkComm#_get_eval_string and executed as a Tcl command.

Constants:

TkCore::INTERP

This is the Tcl/Tk interpreter ( an instance of TclTkIp).

Tk

Included Modules:

TkCore

Extended Modules:

Tk

Module Methods:

Tk.focus(display=nil)

Returns the window that currently has focus. If a window object is given in display, returns the window that currently has focus on the screen on which that window exists.

If no window has the focus, returns the empty string ("").*62

Tk.focus_lastfor(win)

Returns the last window that had the focus, at the same level as window win.

Tk.toUTF8(str,encoding)
Tk.fromUTF8(str, encoding)

Methods:

Because module Tk uses Object#extend on itself, the below methods are also module methods (and in fact it is recommended to use them as module methods).

Tk#root

Returns the root widget. Same as TkRoot.new

Tk#bell

Rings a bell.

Constants:

Tk::TCL_VERSION

The version of Tcl being used.

Tk::TK_VERSION

The version of Tk being used.

Tk::JAPANIZED_TK

Returns true or false depending on whether the Tk version being used is localized for Japanese.

Tk::Scrollable

Methods:

Tk::Scrollable#xscrollcommand(cmd=Proc.new)
Tk::Scrollable#yscrollcommand(cmd=Proc.new)

A widget that includes Tk::Scrollable, when it is scrolled, calls the callback cmd with its scroll position as an argument. Mainly used to move the relevant scrollbar to the right position.

In the case of TkListbox, if there is a drag with mouse button 2 then the block given in xscrollcommand or yscrollcommand is executed.

require "tk"

xscrol = yscrol = nil

list = TkListbox.new {
  ('a'..'z').each {|v|
    insert 'end', (v..'z').to_a.join
  }

  xscrollcommand {|arg| xscrol.set *arg; p arg}
  yscrollcommand {|arg| yscrol.set *arg; p arg}
  grid 'column'=>0, 'row'=>0, 'sticky'=>'nsew'
  focus
}

xscrol = TkScrollbar.new {
  orient "horizontal"
  command {|arg| list.xview *arg; p args}
  grid 'column'=>0, 'row'=>1, 'sticky'=>'ew'
}

yscrol = TkScrollbar.new {
  orient "vertical"
  command {|arg| list.yview *arg; p arg}
  grid 'column'=>1, 'row'=>0, 'sticky'=>'ns'
}
TkGrid.columnconfigure Tk.root, 0, 'weight'=>100
TkGrid.rowconfigure    Tk.root, 0, 'weight'=>100

Tk.mainloop

Please see TkScrollbar#set.*63

The example above is complicated, but the way of controlling scrollbars is mostly (apart from a few special bits) well understood, so making a method like the one below can add a level of abstraction that makes it more pleasant. (At least, the need to define excessive amounts of local variables disappears).

Tk::Scrollable#xview(*index)
Tk::Scrollable#yview(*index)

*64 Change the viewable region of a widget. Usually used to move together with a TkScrollbar, in the block passed to TkScrollbar#command.

The argument can be in one of the forms below:

Tk::Scrollable#xscrollbar(bar=nil)
Tk::Scrollable#yscrollbar(bar=nil)

The motion of the widget and scrollbar can be specified by a combination of Tk::Scrollable#xscrollcommand, Tk::Scrollable#xview, TkScrollbar#command, and TkScrollbar#set, but this method is intended to simplify the process.

The example given for Tk::Scrollable#xscrollcommand, a listbox with scrollbar, can be rewritten using this method as follows:

require "tk"

TkListbox.new {
  ('a'..'z').each {|v|
    insert 'end', (v..'z').to_a.join
  }

  xscrollbar TkScrollbar.new
  yscrollbar TkScrollbar.new
  xscrollbar.grid 'column'=>0, 'row'=>1, 'sticky'=>'ew'
  yscrollbar.grid 'column'=>1, 'row'=>0, 'sticky'=>'ns'
  grid 'column'=>0, 'row'=>0, 'sticky'=>'nsew'
  focus
}

TkGrid.columnconfigure Tk.root, 0, 'weight'=>100
TkGrid.rowconfigure    Tk.root, 0, 'weight'=>100

Tk.mainloop

Tk::Wm

A module for communicating with a window manager. The methods introduced here are normally used as instance methods of TkRoot and TkToplevel.

The behavior of these methods may vary depending on the implementation of the window manager.

Methods:

Tk::Wm#aspect
Tk::Wm#aspect(min_w, min_h, max_w, max_h)

Sets the ratio between the width and height of the window. The arguments are 4 integers: min_w/min_h is the smallest width/height ratio, and max_w/max_h is the biggest. The return value is nil.

To return to the default state (as when aspect ratio has not been set), pass nil in each argument.

If no arguments are given, the method returns the current state in an array. If aspect ratio has not been set, the empty array [] is returned.

require "tk"
p Tk.root.aspect
p Tk.root.aspect 2, 1, 10, 1
p Tk.root.aspect
# Tk.mainloop
p Tk.root.aspect nil, nil, nil, nil
p Tk.root.aspect

=> []
   nil
   [2, 1, 10, 1]
   nil
   []

Tk::Wm#client(name=None)

Informs the window manager that the host executing the script is called name*66. The empty string "" is returned.

If the argument is nil, settings are erased.

If the arguments are omitted, the current settings are returned.

require "tk"
p Tk.root.client
  Tk.root.client "foobar"
p Tk.root.client
  Tk.root.client nil
p Tk.root.client

=> ""
   "foobar"
   ""

Tk::Wm#colormapwindows(*args)
Tk::Wm#wm_command(value=None)
Tk::Wm#deiconify

Makes it so you can see the window.Tk::Wm#withdrawTk::Wm#iconify

Tk::Wm#focusmodel(model=None)

If model is "active", focus will be requested even if focus is on another application.*67

If model is "passive", the window does not request input focus itself but leaves it to the window manager. It seems likely that Tcl/Tk works in this mode.*68

If the argument is omitted, the current settings are returned.

The default focus model is "passive".

require "tk"
p Tk.root.focusmodel
p Tk.root.focusmodel "active"
p Tk.root.focusmodel
Tk.root.focus
Tk.mainloop

Tk::Wm#frame

Returns the Resource ID of the window frame (the part where the window manager draws the title bar etc). See TkWinfo.id

require "tk"
p Tk.root.frame
# Tk.root.overrideredirect true
Tk.after 1000, proc {
  p Tk.root.frame
  # p Tk.root.id
  exit
}
Tk.mainloop

=> "0x0"
   "0xc001dd"

Tk::Wm#geometry(geom=nil)

Sets window geometry. If the argument is omitted, return the current window geometry.

geom is a string of the form "width x height [+-] X_location [+-] Y_location".

require "tk"
p Tk.root.geometry("100x100+0+0")
Tk.after 1000, proc {
  p Tk.root.geometry
  exit
}
Tk.mainloop

=> ""
   "100x100+0+0"

Tk::Wm#grid
Tk::Wm#grid(base_width, base_height, width_inc, height_inc)

Specifies the increment by which to resize the window. In base_width and base_height, which grid has the base size (default 200x200) (TkWinfo.reqheight, TkWinfo.reqwidth) is specified*69. In width_inc and height_inc, the grid units (the increment to use during resizing) are specified in pixels.

The return value when setting values is nil.

To return to the default state (as when the grid has not been set), pass nil in each argument.

If arguments are omitted, the current settings are returned as an array. If no grid is set, the empty array [] is returned.

require "tk"
p Tk.root.grid 4, 4, 50, 50
p Tk.root.grid
# Tk.mainloop
p Tk.root.grid nil, nil, nil, nil
p Tk.root.grid

=> nil
   [4, 4, 50, 50]
   nil
   []

Tk::Wm#group(leader=None)

If a value is given, the window is put into the same group as the leader. If the group leader is iconized, all windows belonging to that group will be iconized (depending on the window manager, they may disappear or not).

If nil is passed, the window's group setting is erased. If the argument is omitted, the current setting is returned.

require "tk"
top = TkToplevel.new
p top.group Tk.root
p top.group
p top.group nil
p top.group
Tk.mainloop

=> nil
   #<TkRoot: @path=".">
   nil
   nil

Tk::Wm#iconbitmap(bitmap=None)

Sets the bitmap displayed in the icon to bitmap.

If nil is passed, the icon's bitmap setting is erased. If the argument is omitted, the current setting is returned. *70

require "tk"
Tk.root.iconify
p Tk.root.iconbitmap "question"
p Tk.root.iconbitmap
Tk.mainloop

=> ""
   "question"

Tk::Wm#iconify

Puts the window into the iconified state.Tk::Wm#deiconifyTk::Wm#withdraw

Tk::Wm#iconmask(bitmap=None)

The icon mask is given in bitmap. If nil is passed, the setting is erased. If the argument is omitted, the current setting is returned.

Tk::Wm#iconname(str=None)

The string to display in the icon is set to str. If nil is passed, the setting is erased. If the argument is omitted, the current setting is returned.

Tk::Wm#iconposition(x=nil, y=nil)

Sets the icon's location.

require "tk"
Tk.root.iconify
Tk.root.iconbitmap "question"
p Tk.root.iconposition
Tk.root.iconposition 100, 100
p Tk.root.iconposition
Tk.mainloop

=> []
   [100, 100]

Tk::Wm#iconwindow(icon=nil)

Makes window icon into an icon. In this case, the return value is nil.

If nil is passed, the setting is erased. If the argument is omitted, the current setting is returned.

Below, a button is made into the icon of the root window. When the button is pressed, the iconization is undone.

require "tk"
icon = TkToplevel.new
TkButton.new(icon) { text "Icon"; command { Tk.root.deiconify } }.pack
p Tk.root.iconwindow icon
p Tk.root.iconwindow
Tk.mainloop

=> nil
   #<TkToplevel: @screen=nil, @path=".w0000", @classname=nil>

Tk::Wm#maxsize
Tk::Wm#maxsize(width, height)

Sets the max size of the window. If the argument is omitted, the current settings are returned as an array.

The default max size for a window is the size of the screen.

require "tk"
p Tk.root.maxsize
p Tk.root.minsize
Tk.mainloop
p Tk.root.maxsize(200,300)
p Tk.root.minsize(20,30)
p Tk.root.maxsize
p Tk.root.minsize
Tk.mainloop

=> [1265, 994]
   [1, 1]
   nil
   nil
   [200, 300]
   [20, 30]

Tk::Wm#minsize
Tk::Wm#minsize(width, height)

Sets the min size of the window. If the argument is omitted, the current settings are returned as an array.

The default min size for a window is 1x1.

Tk::Wm#overrideredirect(bool=None)

If bool is true, do not let the window manager manage the window. Default is false. If the argument is omitted, the current settings are returned.

Tk::Wm#overrideredirect(bool=None)

require "tk"
p Tk.root.overrideredirect
p Tk.root.overrideredirect true
p Tk.root.overrideredirect
Tk.mainloop

=> false
   ""
   true

Tk::Wm#positionfrom(who=None)

who is "program", "user" or an abbreviation of one of those values. If "user" is given, the positioning of the window is according to user supplied settings (including the values in Tk::Wm#geometry )*71.

If nil is passed, the setting is erased. If the argument is omitted, the current setting is returned.

require "tk"
p Tk.root.positionfrom
Tk.root.geometry "+0+0"
p Tk.root.positionfrom
p Tk.root.positionfrom "prog"
p Tk.root.positionfrom
Tk.mainloop

=> ""
   "user"
   ""
   "program"

Tk::Wm#protocol(name=nil, cmd=nil)

On receiving message name from the window manager, execute Proc object cmd.

If cmd is the empty string "", settings are erased.

If cmd is omitted, the proc object specified for name is returned.

If all the arguments are omitted, the protocols that have been set are returned in an array.

require "tk"
p Tk.root.protocol "WM_DELETE_WINDOW", proc {puts "foo"}
p Tk.root.protocol "WM_TAKE_FOCUS",    proc {puts "bar"}
p Tk.root.protocol "WM_DELETE_WINDOW"
p Tk.root.protocol

p Tk.root.protocol "WM_DELETE_WINDOW", ""
p Tk.root.protocol "WM_DELETE_WINDOW"
p Tk.root.protocol
Tk.mainloop

=> ""
   ""
   #<Proc:0x4013685c>
   ["WM_TAKE_FOCUS", "WM_DELETE_WINDOW"]
   ""
   nil
   ["WM_TAKE_FOCUS"]

*72

Tk::Wm#resizable
Tk::Wm#resizable(width, height)

Specifies whether the height and width of window self can be changed by the user. width and height may be either true or false.

If the arguments are omitted, an array [width, height] is returned that tells whether width and height can be changed by the user. The elements of this array are true or false.

Tk::Wm#sizefrom(who=None)

who is "program", "user" or an abbreviation of one of those values. If "user" is given, the size of the window is determined by user settings (including the values in Tk::Wm#geometry )*73.

If nil is passed, the setting is erased. If the argument is omitted, the current setting is returned.

require "tk"
p Tk.root.sizefrom
Tk.root.geometry "100x100"
Tk.after 1000, proc {
  p Tk.root.sizefrom
  p Tk.root.sizefrom "prog"
  p Tk.root.sizefrom
}
Tk.mainloop

=> ""
   ""
   ""
   "program"

Tk::Wm#state

Returns the state of window self as "normal", "iconic", "withdraw", or "icon".

Tk::Wm#title(str=None)

If str is supplied, window self has its title set to str. In such a case the method returns the empty string "".

If the arguments are omitted the current window title is returned. The default window title is "tk", or in the case of TkToplevel, the path. The title can be changed with TkCore.appname but this method is the preferred one.

require "tk"
Tk.appname "bar"
p Tk.root.title
p Tk.root.title "foo"
p Tk.appname
p TkWinfo.appname(Tk.root)
p Tk.root.title
Tk.mainloop

=> "bar"
   ""
   "bar"
   "bar"
   "foo"

Tk::Wm#transient(master=None)

Make window self a transient window of window master.

If nil is passed, the setting is erased. If the argument is omitted, the current setting is returned.

require "tk"
top = TkToplevel.new
p top.transient Tk.root
p top.transient
Tk.mainloop

=> nil
   #<TkRoot: @path=".">

Tk::Wm#withdraw

Make window self no longer be visible.Tk::Wm#deiconifyTk::Wm#iconify

TkClipboard

Included Modules:

Tk

Extended Modules:

Tk

Module Functions

TkClipboard.clear
TkClipboard.get
TkClipboard.set(data)
TkClipboard.append(data)

TkComposite

*74

Using this module, multiple widgets can be grouped together and handled as a single entity. Such a widget (class) is called a composite widget (class).

Example -- a text input class with a label attached:

require "tk"

class TkLabeledEntry < TkEntry
  include TkComposite

  def initialize_composite(*args)
    @label = TkLabel.new(@frame)        # @frame has already been created
    @entry = TkEntry.new(@frame)
    @label.pack('side'=>'left')
    @entry.pack('side'=>'left')
    @path = @entry.path                 # For inheriting TkEntry methods

    delegate('DEFAULT', @entry, @label)
    delegate('text', @label)
  end
  def textvariable(var)
    @label.textvariable var
  end
end

TkLabeledEntry.new {
  text "foobar"
  self.value = "hoge"
  pack
}

Tk.mainloop

@path would be the widget path of @frame by default, but in order to apply the result of the method inherited from TkEntry to the @entry widget, it is changed to the path of @entry. (This is because most methods are implemented to operate on @path)

Included Modules:

Tk

Extended Modules:

Tk

Private Methods:

TkComposite#initialize_composite(*args)

This method is overridden in widgets that include TkComposite, to do initialization. (The initialize method must not be overridden). At the time of object creation, it is called from the new method (or to be precise, the initialize method).

args contains the 2nd argument (and subsequent arguments) to new. (The first argument, the parent widget, is omitted)

At the point when this method is called, the instance method @frame is set to a new TkFrame object. Normally, this frame is laid out with the internal controls that make up the parent widget.

Methods:

TkComposite#epath

Returns the widget path of a composite widget. By default, this is the path to the frame widget.

TkComposite#delegate(option, *wins)

When the option method option is called, makes it so that the call is passed on to the widget specified in wins.

The special option code 'DEFAULT' sets all remaining options to delegate to wins.

TkComposite#configure(slot, value=None)
TkComposite#configure(hash)

Usage is the same as TkObject#configure. As with TkComposite#delegate, sets the options for internal widgets.

TkGrid

A class for arranging widgets according to a grid.

Note that normally, TkWindow#grid can be used to arrange widgets on a grid.

Included Modules:

Tk

Extended Modules:

Tk

Module Functions

TkGrid.bbox(master, column=nil, raw=nil, column2=nil, row2=nil)
TkGrid.configure(widget1, widget2, ..., options=nil)

For each widget N, arranges it as specified in options. options is a hash whose keys are as below:

TkGrid.columnconfigure(master, index, args)

For the master widget master's column location index, set the attributes to args. args is a hash whose keys are as below:

If args is an empty hash {}, the current settings are returned. *75

require "tk"

f = TkFrame.new.pack
p TkGrid.columnconfigure(f, 0, {})

=> "-minsize 0 -pad 0 -weight 0"

*76

TkGrid.rowconfigure(master, index, args)

For the master widget master's row location index, set the attributes to args. args is a hash whose keys are as below:

If args is an empty hash {}, the current settings are returned. *77

require "tk"

f = TkFrame.new.pack
p TkGrid.rowconfigure(f, 0, {})
p TkGrid.rowconfigure(f, 0, {'minsize'=>10})
p TkGrid.rowconfigure(f, 0, {})

=> "-minsize 0 -pad 0 -weight 0"
   ""
   "-minsize 10 -pad 0 -weight 0"

*78

require "tk"

module TkGrid
  def columnconfigure(master, index, args=None)
    Hash[tk_split_list(tk_call "grid", 'columnconfigure', master, index, *hash_kv(args))]
  end

  def rowconfigure(master, index, args=None)
    tk_tcl2ruby(tk_call "grid", 'rowconfigure', master, index, *hash_kv(args))
  end

  module_function :columnconfigure, :rowconfigure
end


f = TkFrame.new.pack
p TkGrid.columnconfigure(f, 0)
p TkGrid.columnconfigure(f, 0, {'minsize'=>10})
p TkGrid.columnconfigure(f, 0)

f = TkFrame.new.pack
p TkGrid.rowconfigure(f, 0)
p TkGrid.rowconfigure(f, 0, {'minsize'=>10})
p TkGrid.rowconfigure(f, 0)

TkGrid.add(widget, *args)
TkGrid.forget(*args)
TkGrid.info(slave)
TkGrid.location(master, x, y)
TkGrid.propagate(master, bool=None)
TkGrid.remove(*args)
TkGrid.size(master)
TkGrid.slaves(args)

TkKinput

Included Modules:

Tk

Extended Modules:

Tk

Class Methods:

TkKinput.start(window, style=None)
TkKinput.send_spot(window)
TkKinput.input_start(window, keys=nil)
TkKinput.attribute_config(window, slot, value=None)
TkKinput.attribute_info(window, slot=nil)
TkKinput.input_end(window)

Methods:

TkKinput#kinput_start(style=None)
TkKinput#kinput_send_spot
TkKinput#kanji_input_start(keys=nil)
TkKinput#kinput_attribute_config(slot, value=None)
TkKinput#kinput_attribute_info(slot=nil)
TkKinput#kanji_input_end

TkManageFocus

A module for handling input focus.*79

require "tk"
require "tkmngfocus"

module Tk
  def Tk.focus_to(to)
    tk_call 'focus', to
  end
  def Tk.focus_prev(window)
    TkManageFocus.prev window
  end
  def Tk.focus_next(window)
    TkManageFocus.next window
  end
end
class TkWindow
  def focus_to_prev
    Tk.focus_to Tk.focus_prev self
  end
  def focus_to_next
    Tk.focus_to Tk.focus_next self
  end
end

TkButton.new { text "A"; bind('Down') { focus_to_next } }.pack.focus
TkButton.new { text "B"; bind('Down') { focus_to_next } }.pack
TkButton.new { text "C"; bind('Down') { focus_to_next } }.pack
TkButton.new { text "D"; bind('Down') { focus_to_next } }.pack
TkButton.new { text "E"; bind('Down') { focus_to_next } }.pack

Tk.mainloop

Extended Modules:

Tk

Class Methods:

TkManageFocus.followsMouse

Change to the mode in which whichever widget the mouse pointer is over has input focus.

TkManageFocus.next(window)

Return the path of the next widget after window in the input focus transition sequence. *80

TkManageFocus.prev(window)

Return the path of the previous widget before window in the input focus transition sequence. *81

Methods:

TkManageFocus#focusNext

Same as TkManageFocus.next self.

TkManageFocus#focusPrev

Same as TkManageFocus.prev self.

TkOption

A module for accessing the option database.

require "tk"
TkLabel.new(nil, "text"=>"label1").pack
TkOption.add("*Label.background", "white")
TkLabel.new(nil, "text"=>"label2").pack
TkOption.clear
TkLabel.new(nil, "text"=>"label3").pack
Tk.mainloop

Included Modules:

Tk

Extended Modules:

Tk

Module Functions

TkOption.add(pat, value, pri=None)

Add a new option to the database. The result of this change does not affect already-created objects. The pri argument can be used to change the option's priority to a value from 0 to 100.

TkOption.clear

Return the changes in the option database back to the defaults.

TkOption.get(win, name, klass)

Get a value from the option database.

TkOption.readfile(file, pri=None)

Read in a resource file such as .Xdefaults.

TkPack

A module for laying out widgets.

Note that normally, TkWindow#pack can be used.

Included Modules:

Tk

Extended Modules:

Tk

Module Functions

TkPack.configure(win1, win2, ... winN, keys=nil)

Position widgets win1 to winN. keysis a hash with the keys below:

TkPack.forget(*args)

Stop arranging the widgets in args (they will no longer be visible).

TkPack.propagate(master, bool=None)

A boolean that determines whether, when the slaves have all been packed, the size of the master widget is automatically changed.

If the arguments are omitted, returns the current setting.

With the default value of true, the master widget may be shrunk and the (space allocated to the) slaves expanded, in order to minimize the amount of empty space.

*82

require "tk"

p TkPack.propagate(Tk.root)
TkButton.new { text "foo" }.pack

top = TkToplevel.new
p TkPack.propagate(top)

TkPack.propagate(top, false)
p TkPack.propagate(top)
TkButton.new(top) { text "bar" }.pack

Tk.mainloop

=> true
   true
   false

In the example below, bar is not displayed:*83

require "tk"

TkFrame.new {
  TkPack.propagate(self, true)
  TkLabel.new(self) { text "foo" }.pack
}.pack

TkFrame.new {
  TkPack.propagate(self, false)
  TkLabel.new(self) { text "bar" }.pack
}.pack

Tk.mainloop

TkPalette

Included Modules:

Tk

Extended Modules:

Tk

Class Methods:

TkPalette.set(*args)
TkPalette.setPalette(*args)
TkPalette.bisque
TkPalette.darken(color, percent)
TkPalette.recolorTree(window, colors)

Methods:

TkPalette#recolorTree(colors)

TkSelection

A module for handling the selection.

Included Modules:

Tk

Extended Modules:

Tk

Class Methods:

TkSelection.handle(win, func, type=None, format=None)

When widget win's selection is taken, handler funcwill be executed. type is the type to be specified when the selection is taken (See TkSelection.get) (default is "STRING").

TkSelection.own(win=None, func=None)

If the arguments are omitted, returns the widget object that owns the selection(if there is no selection, returns nil).

*84

Methods:

TkSelection#handle(func, type=None, format=None)
TkSelection#own(func=None)

Module Functions

TkSelection.clear(win=Tk.root)

Deletes the selection. If win is given, this is done within the screen that is the home of the specified window. Returns an empty string.

TkSelection.get(type=None)

Returns the value of the selection. THe type of this value is the argument type, which is one of these values:

If the arguments are omitted, "STRING" is used as the type.

TkTreatCItemFont

Methods:

TkTreatCItemFont#tagfont_configinfo(tagOrId)
TkTreatCItemFont#tagfont_configure(tagOrId, slot)
TkTreatCItemFont#latintagfont_configure(tagOrId, ltn, keys=nil)
TkTreatCItemFont#kanjitagfont_configure(tagOrId, knj, keys=nil)
TkTreatCItemFont#tagfont_copy(tagOrId, window, wintag=nil)
TkTreatCItemFont#latintagfont_copy(tagOrId, window, wintag=nil)
TkTreatCItemFont#kanjitagfont_copy(tagOrId, window, wintag=nil)

TkTreatFont

Methods:

TkTreatFont#font_configinfo
TkTreatFont#fontobj
TkTreatFont#font_configure(slot)
TkTreatFont#latinfont_configure(ltn, keys=nil)
TkTreatFont#asciifont_configure(ltn, keys=nil)
TkTreatFont#kanjifont_configure(knj, keys=nil)
TkTreatFont#font_copy(window, tag=nil)
TkTreatFont#latinfont_copy(window, tag=nil)
TkTreatFont#asciifont_copy(window, tag=nil)
TkTreatFont#kanjifont_copy(window, tag=nil)

TkTreatMenuEntryFont

Methods:

TkTreatMenuEntryFont#tagfont_configinfo(index)
TkTreatMenuEntryFont#tagfont_configure(index, slot)
TkTreatMenuEntryFont#latintagfont_configure(index, ltn, keys=nil)
TkTreatMenuEntryFont#asciitagfont_configure(index, ltn, keys=nil)
TkTreatMenuEntryFont#kanjitagfont_configure(index, knj, keys=nil)
TkTreatMenuEntryFont#tagfont_copy(index, window, wintag=nil)
TkTreatMenuEntryFont#latintagfont_copy(index, window, wintag=nil)
TkTreatMenuEntryFont#asciitagfont_copy latintagfont_copy(index, window, wintag=nil)
TkTreatMenuEntryFont#kanjitagfont_copy(index, window, wintag=nil)

TkTreatTagFont

Methods:

TkTreatTagFont#font_configinfo
TkTreatTagFont#font_configure(slot)
TkTreatTagFont#latinfont_configure(ltn, keys=nil)
TkTreatTagFont#kanjifont_configure(knj, keys=nil)
TkTreatTagFont#font_copy(window, wintag=nil)
TkTreatTagFont#latinfont_copy(window, wintag=nil)
TkTreatTagFont#kanjifont_copy(window, wintag=nil)

TkTreatTextTagFont

Methods:

TkTreatTextTagFont#tagfont_configinfo(tag)
TkTreatTextTagFont#tagfont_configure(tag, slot)
TkTreatTextTagFont#latintagfont_configure(tag, ltn, keys=nil)
TkTreatTextTagFont#kanjitagfont_configure(tag, knj, keys=nil)
TkTreatTextTagFont#tagfont_copy(tag, window, wintag=nil)
TkTreatTextTagFont#latintagfont_copy(tag, window, wintag=nil)
TkTreatTextTagFont#kanjitagfont_copy(tag, window, wintag=nil)

TkUtil

Module Methods:

TkUtil.eval_cmd(cmd, *rest)

Proc object cmd is executed with rest as arguments.

*85

TkWinfo

A module that collects together methods for obtaining information about a window. The information thus obtained is comparatively low level (close to the window system).

*86

Included Modules:

Tk

Extended Modules:

Tk

Module Methods:

TkWinfo.atom(name)

Returns application name name's atom.

require "tk"
p TkWinfo.atom("tk")

=> 352

*87

TkWinfo.atomname(id)

Returns the application name matching atom id.

require "tk"
p TkWinfo.atomname(TkWinfo.atom("tk"))

=> "tk"

*88

TkWinfo.cells(window)

Returns the cell count of the color map of window window.

require "tk"
p TkWinfo.cells(Tk.root)

=> 64

TkWinfo.children(window)

Returns the children of window in an array.

(Because it is a child of the top of the widget hierarchy, TkToplevel is included among the child windows)

require "tk"
TkFrame.new {
  TkButton.new(self).pack
}
TkToplevel.new {
  TkLabel.new(self).pack
}
p TkWinfo.children(Tk.root)

=> [#<TkFrame: @path=".w0000">, #<TkToplevel: @path= ... >]

TkWinfo.classname(window)

Returns the widget class name.

require "tk"
p TkWinfo.classname Tk.root
p TkWinfo.classname TkFrame.new
p TkWinfo.classname TkFrame.new(nil, "classname"=>"Foo")

=> "Tk"
   "Frame"
   "Foo"

TkWinfo.colormapfull(window)

Returns true if there is no space left in the color map that is allocated among windows.

require "tk"
p TkWinfo.colormapfull Tk.root

=> false

TkWinfo.containing(rootX, rootY)

Returns the window that is at the given location.

require "tk"
TkLabel.new {
  text "Click Here!"
  bind "1", proc {|rootx, rooty|
    p TkWinfo.containing(rootx, rooty)
    exit
  }, "%X %Y"
}.pack
Tk.mainloop

=> #<TkLabel: @path=".w0000", @cmdtbl=["c0000"]>

*89

TkWinfo.depth(window)

Returns the window's depth (the number of bits used to represent 1 pixel).

require "tk"
p TkWinfo.depth TkLabel.new

=> 16

TkWinfo.exist?(window)

Returns whether or not the window exists.

require "tk"
l = TkLabel.new
p TkWinfo.exist? l
l.destroy
p TkWinfo.exist? l

=> true
   false

TkWinfo.fpixels(window, number)

Returns the number of pixels corresponding to the distance number, as a floating point number.TkWinfo.pixels

require "tk"
p TkWinfo.fpixels Tk.root, 1
p TkWinfo.fpixels Tk.root, "1c"  # cm
p TkWinfo.fpixels Tk.root, "1m"  # mm
p TkWinfo.fpixels Tk.root, "1i"  # inch

p TkWinfo.fpixels Tk.root, "2.54c"  # 1 inch

=> 1.0
   29.56120092
   2.956120092
   75.08545035
   75.08545035

TkWinfo.geometry(window)

Returns the window's geometry.

Because Tk::Wm#geometry returns the position of the window frame (title bar etc), the result of this method is sometimes different.

require "tk"
p Tk.root.geometry 
p TkWinfo.geometry Tk.root
Tk.after 1000 do
  p Tk.root.geometry
  p TkWinfo.geometry Tk.root
  exit
end
Tk.mainloop

=>"1x1+0+0"
  "1x1+0+0"
  "200x200+323+374"
  "200x200+328+396"

TkWinfo.height(window)

Returns the height of the window.

require "tk"
Tk.after 1000 do
  p TkWinfo.height Tk.root
  p TkWinfo.width Tk.root
  exit
end
Tk.mainloop

=> 200
   200

TkWinfo.id(window)

Returns the Resource ID of the window.TkWinfo.widget

require "tk"
p TkWinfo.id Tk.root
p TkWinfo.widget TkWinfo.id Tk.root

=> "0x400000e"
   #<TkRoot: @path=".">

TkWinfo.interps(window=nil)

Returns the application names of running Tcl/Tk interpreters in an array. If a window is specified, it returns those that are running on the screen that contains that window.

require "tk"
ip = TclTkIp.new
p TkWinfo.interps

=> ["tk #2", "tk"]

TkWinfo.mapped?(window)

Returns true if the window is mapped. TkWinfo.viewable

require "tk"
p TkWinfo.mapped? Tk.root
Tk.after 1000 do
  p TkWinfo.mapped? Tk.root
  exit
end
Tk.mainloop

=> false
   true

TkWinfo.manager(window)

Returns the name of the geometry manager that is arranging the windows. In the case of TkRoot and TkToplevel, a string showing the name of the window manager ("wm") is returned.

require "tk"
p TkWinfo.manager Tk.root
p TkWinfo.manager TkToplevel.new
p TkWinfo.manager TkLabel.new.pack
p TkWinfo.manager TkLabel.new.grid
p TkWinfo.manager TkLabel.new.place("x"=>0)

=> "wm"
   "wm"
   "pack"
   "grid"
   "place"

TkWinfo.appname(window)

Returns the window name (an element in the path). For the root widget, returns the application name. See TkCore.appname

require "tk"
p TkWinfo.appname Tk.root
p TkWinfo.appname TkLabel.new.pack

=> "tk"
   "w0001"

TkWinfo.parent(window)

Returns the window's parent window. For the root widget, returns nil.

require "tk"
p TkWinfo.parent TkRoot.new
p TkWinfo.parent TkToplevel.new

=> nil
   #<TkRoot: @path=".">

TkWinfo.widget(id)

Returns a window, given a window's Resource ID. See TkWinfo.id

require "tk"
p TkWinfo.id Tk.root
p TkWinfo.widget TkWinfo.id Tk.root

=> 62914574
   #<TkRoot: @path=".">

*90

TkWinfo.pixels(window, number)

Returns the number of pixels equivalent to distance number as an integer.TkWinfo.fpixels

require "tk"
p TkWinfo.pixels Tk.root, 1
p TkWinfo.pixels Tk.root, "1c"  # cm
p TkWinfo.pixels Tk.root, "1m"  # mm
p TkWinfo.pixels Tk.root, "1i"  # inch

p TkWinfo.pixels Tk.root, "2.54c"  # 1 inch

=> 1
   30
   3
   75
   75

TkWinfo.reqheight(window)

Returns the height requested by the window.

require "tk"
p TkWinfo.height Tk.root
p TkWinfo.reqheight Tk.root

=> 1
   200

TkWinfo.reqwidth(window)

Returns the width requested by the window.

require "tk"
p TkWinfo.width Tk.root
p TkWinfo.reqwidth Tk.root

=> 1
   200

TkWinfo.rgb(window, color)

Returns the RGB value matching color as an array.

require "tk"
p TkWinfo.rgb Tk.root, "black"
p TkWinfo.rgb Tk.root, "white"
p TkWinfo.rgb Tk.root, "red"
p TkWinfo.rgb Tk.root, "green"
p TkWinfo.rgb Tk.root, "blue"
p TkWinfo.rgb Tk.root, "gray"
p TkWinfo.rgb Tk.root, "#0a0a0a"

=> [0, 0, 0]
   [65535, 65535, 65535]
   [65535, 0, 0]
   [0, 65535, 0]
   [0, 0, 65535]
   [48830, 48830, 48830]
   [2114, 2114, 2114]


TkWinfo.rootx(window)

Returns the X coordinate of the window's base location (top left corner) relative to the root window. *91

require "tk"
Tk.root.geometry("+0+0")
p TkWinfo.rootx Tk.root
p TkWinfo.rooty Tk.root
Tk.after 1000, proc {
  p TkWinfo.rootx Tk.root
  p TkWinfo.rooty Tk.root
  exit
}
Tk.mainloop

=> 0
   0
   5
   22

TkWinfo.rooty(window)

Returns the Y coordinate of the window's base location (top left corner) relative to the root window.

TkWinfo.screen(window)

Returns the name of the screen in which the window lives.

require "tk"
p TkWinfo.screen Tk.root

=> ":0.0"

TkWinfo.screencells(window)

Returns the cell count of the default color map for the screen in which the window lives.

require "tk"
p TkWinfo.screencells Tk.root

=> 64

TkWinfo.screendepth(window)

Returns the default depth of the screen in which the window lives.

require "tk"
p TkWinfo.screendepth Tk.root

=> 16

TkWinfo.screenheight (window)

Returns the height in pixels of the screen in which the window lives.

require "tk"
p TkWinfo.screenheight Tk.root

=> 1024

TkWinfo.screenmmheight(window)

Returns the height in millimetres of the screen in which the window lives.

require "tk"
p TkWinfo.screenheight Tk.root
p TkWinfo.screenmmheight Tk.root
p TkWinfo.fpixels Tk.root, "#{TkWinfo.screenmmheight Tk.root}m"

=> 1024
   347
   1025.773672

*92

TkWinfo.screenmmwidth(window)

Returns the width in millimetres of the screen in which the window lives.

require "tk"
p TkWinfo.screenwidth Tk.root
p TkWinfo.screenmmwidth Tk.root
p TkWinfo.fpixels Tk.root, "#{TkWinfo.screenmmwidth Tk.root}m"

=> 1280
   433
   1280.0

TkWinfo.screenvisual(window)

Returns the default visual class of the screen in which the window lives. The visual class is one of the following:

*93

require "tk"
p TkWinfo.screenvisual Tk.root

=> "truecolor"

TkWinfo.screenwidth(window)

Returns the width in pixels of the screen in which the window lives.

require "tk"
p TkWinfo.screenwidth Tk.root

=> 1280

TkWinfo.server(window)

Returns server information (version, vendor, vendor version) as a string, for the screen in which the window lives.

require "tk"
p TkWinfo.server Tk.root

=> "X11R0 The XFree86 Project, Inc 3320"

*94

TkWinfo.toplevel(window)

If the window is positioned on a TkToplevel, returns that TkToplevel.

require "tk"
p TkWinfo.toplevel TkFrame.new.pack

TkToplevel.new {
  p TkWinfo.toplevel TkFrame.new(self) {
    p TkWinfo.toplevel TkFrame.new(self).pack
  }.pack
}

=> nil
   #<TkToplevel: @classname=nil, @path=".w0001", @screen=nil>
   #<TkToplevel: @classname=nil, @path=".w0001", @screen=nil>

TkWinfo.visual(window)

Returns the visual class of the window.

require "tk"
p TkWinfo.visual TkFrame.new
p TkWinfo.visual TkToplevel.new(nil, {"visual"=>"grayscale"})

=> "truecolor"
error--> tk.rb:510:in `_invoke': couldn't find an appropriate visual (RuntimeError)

*95

TkWinfo.visualid(window)

Returns the visual ID of the window.

require "tk"
p TkWinfo.visualid TkFrame.new
p TkWinfo.visualid TkToplevel.new(nil, {"visual"=>"grayscale"})

=> "0x22"
error--> tk.rb:510:in `_invoke': couldn't find an appropriate visual (RuntimeError)

*96

TkWinfo.visualsavailable(window, includeids=false)

An array as below, showing what properties can be set on the screen:

[visual class , depth (bits per pixel), visual ID]

visual ID is only included if includeids is true.

In old Tk versions (at least in version 4.0), visual ID is not one of the elements. *97

require "tk"
p TkWinfo.visualsavailable TkFrame.new
p TkWinfo.visualsavailable TkFrame.new, true

=> [["truecolor", 16]]
   [["truecolor", 16, "0x22"]]

TkWinfo.vrootheight(window)

Returns the height of the screen which holds the window. Allows for virtual screen.

require "tk"
p TkWinfo.vrootheight Tk.root

=> 1024

TkWinfo.vrootwidth(window)

Returns the width of the screen which holds the window. Allows for virtual screen.

require "tk"
p TkWinfo.vrootwidth Tk.root

=> 1280

TkWinfo.vrootx(window)

Returns the X-coordinate of the screen which holds the window. Allows for virtual screen

require "tk"
p TkWinfo.vrootx Tk.root

=> 0

TkWinfo.vrooty(window)

Returns the Y-coordinate of the screen which holds the window. Allows for virtual screen

require "tk"
p TkWinfo.vrooty Tk.root

=> 0

TkWinfo.width(window)

Returns the width of the window.

require "tk"
Tk.after 1000 do
  p TkWinfo.height Tk.root
  p TkWinfo.width Tk.root
  exit
end
Tk.mainloop

=> 200
   200

TkWinfo.x(window)

Returns the X coordinate of the window's base location (top left corner) relative to the parent window. For TkRoot and TkToplevel windows, the same as TkWinfo.rootx.

require "tk"
top = TkToplevel.new
label = TkLabel.new {text "label"}.place("x"=>100, "y"=>100)
Tk.after 1000 do
  print TkWinfo.x(Tk.root), '+', TkWinfo.x(label), '=', TkWinfo.rootx(label), "\n"
  print TkWinfo.y(Tk.root), '+', TkWinfo.y(label), '=', TkWinfo.rooty(label), "\n"
  exit
end
Tk.mainloop

=> 226+100=326
   464+100=564

TkWinfo.y(window)

Returns the Y coordinate of the window's base location (top left corner) relative to the parent window. ForTkRoot and TkToplevel windows, the same as TkWinfo.rooty.

TkWinfo.viewable(window)

Returns true if the window and all its ancestors are mapped. See TkWinfo.mapped?

require "tk"
root  = TkRoot.new
top   = TkToplevel.new

label1 = TkLabel.new(root) { text "label1" }.pack
label2 = TkLabel.new(top)  { text "label2" }.pack

root.withdraw
Tk.after 1000, proc {
  p TkWinfo.viewable root
  p TkWinfo.viewable label1
  p TkWinfo.viewable top
  p TkWinfo.viewable label2
  exit
}
Tk.mainloop

=> false
   false
   true
   true

TkWinfo.pointerx(window)

Returns the X coordinate of the mouse pointer on the screen that contains the window. Returns -1 if the pointer is not on that screen.*98

require "tk"
p TkWinfo.pointerx Tk.root
p TkWinfo.pointery Tk.root
p TkWinfo.pointerxy Tk.root

=> 493
   556
   [493, 556]

TkWinfo.pointery(window)

Returns the X coordinate of the mouse pointer on the screen that contains the window. Returns -1 if the pointer is not on that screen.*99

TkWinfo.pointerxy(window)

Returns an array: [TkWinfo.pointerx, TkWinfo.pointery]

Methods:

This module's instance methods are the same as the module methods with the same names. However, module methods that have "winfo_" on their names and take a window argument differ in that they operate on self instead.

TkWinfo#winfo_atom(name)

TkWinfo.atom

TkWinfo#winfo_atomname(id)

TkWinfo.atomname

TkWinfo#winfo_cells

TkWinfo.cells

TkWinfo#winfo_children

TkWinfo.children

TkWinfo#winfo_classname

TkWinfo.classname

TkWinfo#winfo_colormapfull

TkWinfo.colormapfull

TkWinfo#winfo_containing(x, y)

TkWinfo.containing

TkWinfo#winfo_depth

TkWinfo.depth

TkWinfo#winfo_exist?

TkWinfo.exist?

TkWinfo#winfo_fpixels(number)

TkWinfo.fpixels

TkWinfo#winfo_geometry

TkWinfo.geometry

TkWinfo#winfo_height

TkWinfo.height

TkWinfo#winfo_id

TkWinfo.id

TkWinfo#winfo_interps

TkWinfo.interps

TkWinfo#winfo_mapped?

TkWinfo.mapped?

TkWinfo#winfo_manager

TkWinfo.manager

TkWinfo#winfo_appname

TkWinfo.appname

TkWinfo#winfo_parent

TkWinfo.parent

TkWinfo#winfo_widget(id)

TkWinfo.widget

TkWinfo#winfo_pixels(number)

TkWinfo.pixels

TkWinfo#winfo_reqheight

TkWinfo.reqheight

TkWinfo#winfo_reqwidth

TkWinfo.reqwidth

TkWinfo#winfo_rgb(color)

TkWinfo.rgb

TkWinfo#winfo_rootx

TkWinfo.rootx

TkWinfo#winfo_rooty

TkWinfo.rooty

TkWinfo#winfo_screen

TkWinfo.screen

TkWinfo#winfo_screencells

TkWinfo.screencells

TkWinfo#winfo_screendepth

TkWinfo.screendepth

TkWinfo#winfo_screenheight

TkWinfo.screenheight

TkWinfo#winfo_screenmmheight

TkWinfo.screenmmheight

TkWinfo#winfo_screenmmwidth

TkWinfo.screenmmwidth

TkWinfo#winfo_screenvisual

TkWinfo.screenvisual

TkWinfo#winfo_screenwidth

TkWinfo.screenwidth

TkWinfo#winfo_server

TkWinfo.server

TkWinfo#winfo_toplevel

TkWinfo.toplevel

TkWinfo#winfo_visual

TkWinfo.visual

TkWinfo#winfo_visualid

TkWinfo.visualid

TkWinfo#winfo_visualsavailable(includeids=false)

TkWinfo.visualsavailable

TkWinfo#winfo_vrootheight

TkWinfo.vrootheight

TkWinfo#winfo_vrootwidth

TkWinfo.vrootwidth

TkWinfo#winfo_vrootx

TkWinfo.vrootx

TkWinfo#winfo_vrooty

TkWinfo.vrooty

TkWinfo#winfo_width

TkWinfo.width

TkWinfo#winfo_x

TkWinfo.x

TkWinfo#winfo_y

TkWinfo.y

TkWinfo#winfo_viewable

TkWinfo.viewable

TkWinfo#winfo_pointerx

TkWinfo.pointerx

TkWinfo#winfo_pointery

TkWinfo.pointery

TkWinfo#winfo_pointerxy

TkWinfo.pointerxy

TkcTagAccess

Included Modules:

TkComm

TkTreatTagFont

Methods:

TkcTagAccess#addtag(tag)
TkcTagAccess#bbox
TkcTagAccess#bind(seq, cmd=Proc.new, args=nil)
TkcTagAccess#bindinfo(seq=nil)
TkcTagAccess#cget(option)
TkcTagAccess#configure(key, value=None)
TkcTagAccess#configinfo(key=nil)
TkcTagAccess#coords(*args)
TkcTagAccess#dchars(first, last=None)
TkcTagAccess#dtag(tag_to_del=None)
TkcTagAccess#find
TkcTagAccess#list
TkcTagAccess#focus
TkcTagAccess#gettags
TkcTagAccess#icursor(index)
TkcTagAccess#index(index)
TkcTagAccess#insert(beforethis, string)
TkcTagAccess#lower(belowthis=None)
TkcTagAccess#move(xamount, yamount)
TkcTagAccess#raise(abovethis=None)
TkcTagAccess#scale(xorigin, yorigin, xscale, yscale)
TkcTagAccess#select_adjust(index)
TkcTagAccess#select_from(index)
TkcTagAccess#select_to(index)
TkcTagAccess#itemtype

TkCallbackBreak

If this exception is raised during execution of an event callback function, all callback functions are aborted. Unlike with TkCallbackContinue, the event callback function bound to the widget class is not called. (See TkWindow#bindtags)

The Tk.callback_break (Actually, TkCore#callback_break) is the method that raises this exception.

In the example below, a left click on the button would originally have output

"bind"
"appended bind"
"class bind"

but in fact because of the call to Tk.callback_break nothing will happen at all. (The button will not even appear pressed-in. This is because that action is carried out by a callback function bound to the TkButton class.)

require "tk"
b1 = TkButton.new { text "click me!" } .pack
Tk.module_eval { _bind ["bind", b1.type], "1", proc {p "class bind"} }
b1.bind "1", proc {Tk.callback_break; p "bind"}
b1.bind_append "1", proc {p "appended bind"}
Tk.mainloop

Superclass:

StandardError

TkCallbackContinue

If this exception is raised in the middle of executing an event callback function and the current callback function is interrupted, the event callback bound to the widget class (or wherever) is run. (See TkWindow#bindtags)

The Tk.callback_continue method (Actually, TkCore#callback_continue) is the method that raises this exception.

In the example below, a left click would originally output

"bind"
"appended bind"
"class bind"

but in fact due to the call to Tk.callback_continue, only

"class_bind"

will be output. (Because the TkButton class' callback function has been replaced, even if left-clicked the button will not change to its pressed-in appearance).

require "tk"
b1 = TkButton.new { text "click me!" } .pack
Tk.module_eval { _bind ["bind", b1.type], "1", proc {p "class bind"} }
b1.bind "1", proc {Tk.callback_continue; p "bind"}
b1.bind_append "1", proc {p "appended bind"}
Tk.mainloop

Superclass:

StandardError

TkCombobox

tkcombobox.rb was not a standard part of ruby as of 1999-12-02. Starting in [ruby-list:18167], Takaaki Tateishi <ttate@jaist.ac.jp> created it.

require 'tkcombobox'
combo = TkCombobox.new(nil,'fg' => 'black','width' => 30)
combo.entry['fg'] = 'blue'
combo.entries = ['entry1', 'entry2', 'entry3']
combo.select_proc = proc{|index,entry| print("index=#{index}, entry=#{entry}\n")}
combo.pack
Tk.mainloop

Superclass:

TkEntry

Included Modules:

TkComposite

Methods:

TkCombobox#initialize_composite(keys=nil)
TkCombobox#doubleclicked_scrollbox(y)
TkCombobox#cmd_scrollbox
TkCombobox#show_scrollbox(entries = nil)
TkCombobox#hide_scrollbox

Tcl/Tk Glossary

Tcl/Tk specific terms that occur in this manual are collected here. I have no particular intention of making any jokes :-)

Tcl List

In Tcl, a list is a string (mind you, everything's a string). Each whitespace-separated token (when evaluated as a list) is interpreted as an element in a list. Also, in a list strings enclosed in "{" and "}" form a list of lists. I feel as if this topic is too hard to understand.

"a" is both the string "a" and at the same time a list containing the single element "a".

"a {b c}" is also a string, and at the same time a list containing the elements "a" and "b c", and furthermore, "b c" is a list containing the elements "b" and "c".

TkComm#tk_split_list and TkComm#list see the first string differently, as a string and as a list respectively.

require "tk"
Tk.module_eval {
  p tk_split_list("a")       # => "a"
  p tk_split_list("a {b c}") # => ["a", ["b", "c"]]

  p list("a")                # => ["a"]
  p list("a {b c}")          # => ["a", ["b", "c"]]
}

In Tcl, "" and {} are both just quotes so a, "a" and {a} are all the same; but let's leave it there. This manual is supposed to focus on Tk, after all...

Tcl Array

Tcl implements arrays as associative arrays. With 'key' being an arbitrary string, usage is as below:

set array(key) value ;# set value 
set array(key)       ;# read value
puts $array(key)     ;# read value

Used in accordance with the Tcl command array.

= X Window System

The de-facto standard windowing system on UNIX. It's just a tad complicated. Often just called 'X'.

Active

A widget state

Atom

In the X Window System, there is a system for converting names (strings) to numerical values to make them easy to handle in C (I hear). These numerical values are called atoms. (man page: see XInternAtom(3))

Application Name

See TkCore#appname

Anchor

There are 2 kinds of anchors. One is what specifies the location of things positioned using the -anchoroptions. The other is related to the selection... but I don't really know how to explain it... See TkListbox.

Event

Virtual Event

Event Callback Function

A callback function assigned to an Event.

Event sequence

The Tcl representation of the flow of a sequence of events. Pressing Escape and then a looks like this when shown as an event sequence:

<Escape><a>

In Tcl/Tk, this event sequence could have its own event callback function registered for it.

#!/usr/local/bin/wish
bind . <Escape><a> { puts "%X %Y" }

In Ruby/Tk, this is represented as an array of event identifiers (See TkBindCore#bind) (Implemented in TkComm#tk_event_sequence.)

Widget

Components such as buttons and labels. In Tcl/Tk, also includes windows. In this manual, windows may be called widgets and vice versa. This distinction in the text has no particular meaning.

Widget class name

In Tcl each widget has a class, and the classes have various names.

button .b
puts [winfo class .b]

=> Button

The class name is used in assigning Event callback functions and Options with a widget.

In Ruby/Tk, to obtain this name, just as in the Tcl/Tk examples you can use TkWinfo.classname (Other methods include to_eval and TkWindow::WidgetClassName)。

Widget Command

General term for a command that changes a widget's action. configure is an example.

In Tcl scripts, the format

Widget_path Widget_command Arguments

is used.

In the Tcl/Tk script below, flash is the widget command.

button .b1 -text "button1"
.b1 flash

In Ruby/Tk, widget commands take the form of methods on a widget.

b1 = Button.new("text"=>"button")
b1.flash

Widget Status

With the state option, a widget's status can be modified. Widget status can be one of the values below:

See TkButton#state etc

Widget Path

The name that identifies an individual widget. In Tcl/TK, an expression like

.top.frame.button

identifies a widget instance using a hierarchical structure. In this manual, such expressions are called widget paths (or sometimes just 'paths').

TkObject#path is the method that returns a path.

require "tk"

TkToplevel.new {
  TkFrame.new(self) {
    b1 = TkButton.new(self, "text"=>"button").pack
    p b1.path
  }.pack
}
Tk.mainloop

=> ".w0000.w0001.w0002"

In Ruby/Tk programming, these paths shouldn't generally appear (in theory).

Widget Hierarchy

Parent-child relationships among widgets. The expression emphasizes the fact that these form a hierarchical structure. *100

Options

Attributes of a widget such as background color and shape. In Tcl/Tk this sort of attribute is set via arguments to the class command and widget command configure. Option names can be abbreviated as long as they are still unique ("activeforeground" -> "activef")。

In Ruby/Tk, options are implemented as methods. They can also be set by the hash that is the 2nd argument to new.

Option database

In the X Window System things like resources are managed be the *101 option command. (In Ruby/Tk, the TkOption module).

Key Symbol

In the X Window System, keys have a symbol name attached to them. You can find them in the /usr/include/X11/keysymdefs.h file and the commands xev and xmodmap -pke among other places. (Normally, things taken by "XK_" are called key symbols.)

Keyboard focus

The state of being able to receive events generated from the keyboard, such as the input of characters. To set the focus, use the focus command. In Ruby/Tk, this corresponds to the Tk.focus and TkWindow#focus methods.

With the default keybindings, the TAB key is used to change focus.

Class

Tcl/Tk is a language well aware of the object oriented approach, so it has classes (unlike plain Tcl). They are closely connected with the setting of Options. See Widget Class Names

Class Command

Tcl commands that create a widget. Used in the form

Class_Command Widget_Path Option_Value_1 Option_Value_2 ...

.

button is such a command.

button .b1 -text "button1"

Class commands correspond to Widget_Class.new in Ruby/Tk.

TkButton.new(nil, "text"=>"button1")

Clipboard

A fancy Selection. It's best-known use is for cutting and pasting. I don't really know how it's different from a Selection.

Callback
Callback Function

In Ruby, these are Proc objects.

I don't know the exact definition, but it has something to do with storing the 'data' for a function and then later on using that data to call the function. See Event Callback Function

Geometry

The size and location information for a window, or a text string that contains that information. (Format: "XxY+width+height")。

Geometry Manager

Something that manages the positioning of a widget. Tcl/Tk manages this via the pack, place, and grid commands.

Selection

The mechanism by which X enables data interchange within and between applications. Its main -- or at least, best-known -- use is in cutting and pasting.

See Clipboard

Choice

Something that sets the Selection.

Title

The string shown in the title bar.

Tag List

Every widget has a tag list; it's where the callback function executed when an event has occurred is searched for.

For instance, by default the button tag list looks like:

button .b1
puts [bindtags .b1]

=> .b1 Button . all

(bindtags is the command to read and set the tag list). An event callback function is defined for each tag above, but the point of a taglist like this is to define, for a given event:

Because a tag can be any string, it is possible to add a taglist that includes custom tags. This allows you to define:

Disable

A Widget status

Transient Window

The behavior of a transient window depends on the implementation of the window manager, but normally:

'transient' is used to indicate a window for a popup menu.

Path

See Widget path

Focus

See Keyboard focus

Procedure

What is called a function in C. In Tcl a procedure is defined like this:

proc name {arg,...} {
  ...
}

Map

A term used in the X Window System Just think of it as meaning 'to display something'.

If a given widget is mapped, its ancestors must all be mapped.

Resource

In the X Window System this word has two meanings. One means a window attribute defined somewhere like .Xdefaults or .Xresources. The other means a resource such as a window or font that is managed by X.

Resource ID

In the X Window System, a resource is managed via an identifier known as a resource ID. I think they're actually pointers, but I don't know the details.

I think there are hardly any places in Ruby/Tk where you would have to know about this.

Root Widget

In Tcl/Tk, the widget at the top of the Widget hierarchy. Has a Widget path of ".". In the original Tcl/Tk terminology, it's called the Main Window, but in this manual it's called the 'root' by association with the TkRoot class.

Virtual Events

Events

Virtual Screens
Distance
Units of Distance

*102

TkWinfo.pixels

Input focus

Keyboard focus


*1Can the main loop be run for each interpreter? It probably can, but no check
*2Probably It's probably something like that.
*3Even if configure is used instead of configure_cmd, there seems to be no problem. Is there any point in configure_cmd existing? Something like that. It just means it can go either way around.
*4In greater detail...
*5Is it being used? It is used via 'super', in the 'def destroy' method of TkWindow,
*6Need to say something about how it is specified.
*7Need to say something about how it is specified.
*8In tk.rb, subclasses of TkWindow do not make this a private method -- why not? It is now private
*9Is it actually repositioned? What was going on??? In any case, I don't think there's a problem.
*10Confirmed in Tk8.0 Now a deleted option. At least in versions of Tk from 8.0 onwards it can't be used, so it would probably be OK to get rid of it. Or maybe give a warning?
*11What would be a good example?
*12Is that really the intention? It's because it collides with a class method.
*13not implement Fixed, so as to correctly return a number.
*14What's the behavior when inputting a multibyte string?
*15How is flush different from below?
*16 Or combo box?
*17dummy
*18Actually, a method of TkWindow, but written here depending on circumstances.
*19What is the correct term?
*20What is the correct term?
*21What is the correct term?
*22What is the correct term?
*23For now, in the following description the behavior of 'listbox' is used. The behavior of 'text' should be checked too.
*24Perhaps a numeric value should be returned in the case of TkListBox?
*25In greater detail...
*26In agreement with the label?
*27In the example above, there is a part in which the order of execution of the event callback functions ought to be explained.
*28This might not be true.
*29dummy
*30Is it really just this?
*31Further methods that include this one should be private, I would think? Quite right -- changed it to private.
*32Need a list of the bitmaps that are available as standard
*33The following methods should probably be private? Quite right -- changed it to private.
*34The behavior of Tcl arrays seems to be unstable. Numbers and strings can be made into Tcl values directly. Array and Hash become associative arrays (in the case of Array, the keys are the indexes). There was the idea of converting Arrays to Tcl lists, but to allow Ruby-style index access, it was made the way it is.
*35Unless this is used while keeping Tcl scope in mind, access will not be possible. With current Tcl arrays, access is not possible. I think it is possible:


------------------------------------------
        Tk.tk_call('namespace', 'children') #==> "::auto_mkindex_parser"
        v = TkVarAccess.new('::auto_mkindex_parser::aaa', 3)
        Tk.tk_call('namespace', 'eval', '::auto_mkindex_parser',
                   'set', 'aaa') #==> "3"
        v.value #==> "3"
        ------------------------------------------
        Tk.tk_call('set', 'aaa(0)', 1)
        Tk.tk_call('set', 'aaa(1)', 2)
	v = TkVarAccess.new('aaa')
	v[0] #==> "1"
	v[1] #==> "2"
        ------------------------------------------
  

*36In the case of 'Visibility' it's different.
*37The RCS ID is "$XConsortium: X.h,v 1.69 94/04/17 20:10:48 dpw Exp $". X.h was described in the original.
*38What happens on windows and macs?
*39To return a Fixnum is surely not desirable behavior. Fixed to look at the event callback function and convert to the appropriate type.
*40The RCS ID is "$XConsortium: X.h,v 1.69 94/04/17 20:10:48 dpw Exp $". X.h was described in the original.
*41Surely it would be better to return a string? What about windows and macs? Defined constants in the TkComm::Event::TypeNum module
*42This explanation is very dubious and must be rechecked... specially an explanation of the arguments...
*43Needs to be clarified as there are 2 kinds of IDs... after_id -> "after#N"、 ID -> "aNNNN"
*44aNNNN
*45Is the example a bit too complex?
*46What?
*47aXXXX
*48I don't really understand the meaning of window
*49dummy
*50Can't specify anything about the format of iterators Made this possible
*51Key symbol?
*52In Tcl/Tk, by overriding the bgerror procedure it is possible to delegate the handling of an error raised in a callback function to the user. What about Ruby/Tk? Added set_handler to make it possible to set an error handler.
*53really??
*54Is this ok? Changed it to raise an exception if it does not get a base 10 number.
*55Need to write about proc rb_out
*56Isn't this a private method? Made it private.
*57Isn't this a private method? Made it private.
*58Isn't this a private method? Made it private.
*59Isn't this a private method? Made it private.
*60Isn't this a private method? Made it private.
*61Or so it says in the manual -- but it seems as if you _can_ specify it.
*62Should it return nil? Changed it to convert to an object if it matches /^\./, otherwise return nil.
*63Need to write about the format of the argument passed to the block.
*64Needs to be corrected
*65???
*66Really? Attribute WM_CLIENT_MACHINE should be checked... Changed it to return the string that was set, when setting the value.
*67In fact if you try it, you can no longer get input focus. Nothing can work if Tcl/Tk won't work -- in other words there's nothing that can be done on the Ruby side.
*68Probably, because of this if you make it 'active' you can't get the input focus. This could be the window manager's fault. I don't really know. Nothing can work if Tcl/Tk won't work -- in other words there's nothing that can be done on the Ruby side.
*69Hrm, I don't really understand this.
*70Doesn't it use TkBitmapImage? You can set a bitmap file in the way shown below:
        ------------------------------------------
        Tk.root.iconbitmap '@/usr/share/tgif/tgificon.xbm'
        ------------------------------------------
This is because TkBitmapImage is an 'image' not a 'bitmap'. The value of the 'bitmap' attribute can't be set.

*71really?
*72Need to write a list of protocol names
*73really?
*74I referred to the explanation in [ruby-list:5610]
*75The default value of args should be TkComm::None To get information, use columnconfiginfo
*76I want to make the return value a hash. columnconfiginfo is returned as a hash
*77The default value of args should be TkComm::None To get information, use rowconfiginfo
*78I want to make the return value a hash. rowconfiginfo is returned as a hash
*79I think the methods shown here should be in module Tk. Added TkFocus.next and TkFocus.new
*80I think it would be better to return the widget object. Quite right. Changed it to return an object.
*81I think it would be better to return the widget object. Quite right. Changed it to return an object.
*82I don't see how this method is useful. If you want to fix the master size, can't you set it with 'geometry'? For example, on the ruby_talk ML there was the question about getting a happy outcome from setting 'propagate' after layout is done, where if a text widget's 'minsize' is set, the window is set to that minimum size. To prevent this, after laying out the text widget with the usual size, and setting 'propagate' so as to prevent the propagation of the size, only then set 'minsize'. Because of 'geometry' being set, I don't think it will work out very well.
*83Why? This needs to be investigated properly. If the display area is insufficient, the 'pack' order makes later objects disappear.
*84What about when an argument is given?
*85Why is this module necessary?
*86What happens on MS Windows?
*87What about displayof? Changed it so that this is supported.
*88What about displayof? Changed it so that this is supported.
*89What about displayof? Changed it so that this is supported.
*90What about displayof? Changed it so that this is supported.
*91Are window decorations not considered?
*92Where is the measurement error?
*93dummy
*94 R0 ?
*95How do you specify a visual class other than truecolor? You can confirm which visual classes can be used, with TkWinfo.visualsavailable. On Unix (X) you can confirm with xdpyinfo. The format to use is in the man page for 'Tk_GetVisual'. For instance, to set 'depth 8' for the DirectColor class, you could set the 'visual' attribute to either the string 'directcolor 8' or the array ['directcolor', 8].
        ------------------------------------------
        t = TkToplevel.new(:visual=>'truecolor 8')
        f = TkFrame.new(:parent=>t, :visual=>'directcolor 4')
        ------------------------------------------
Because the array is converted to a list when passed to the Tk interpreter, the interpreter will hear the same thing whichever way you specify it.

*96How do you specify a visual class other than truecolor? As above.
*97In which version did it become possible to specify "includeids"?
*98In what situation?
*99In what situation?
*100really?
*101?
*102dummy