Man Pages ~~~~~~~~~ Man (or perldoc) pages for the actual widgets are of the form Tk::WidgetName, and are obvious from the name. These are some manpages whose names are not so obvious: Tk List of other documentation, without descriptions Tk::option Functions to read and set options Tk::options List of options common to all widgets Tk::bind callbacks for X events, functions and events Tk::bindtags additional binding function Tk::after Execute callback after delay Tk::fileevent File event callbacks Tk::callbacks forms of callback allowed Tk::event virtual events, generating events manually Tk::Widget Methods applicable to all widgets Tk::Wm Functions for interacting with the windowmanager Tk::grab All about grabbing focus Tk::Tcl-perl some general tcl/perl difference comments Tk::UserGuide an attempt at basic info Tk::overview a shallow introduction to Perk/Tk Tk::Submethods method aliasing Tk::composite Creating a composite widget Tk::Configspecs Configure for composite widgets Tk::CmdLine Command line parsing Tk::Event Unfinished? documentation on event handling URLs ~~~~ http://www.perltk.org/ http://www.xray.mpe.mpg.de/mailing-lists/ptk/ http://rainbow.ldgo.columbia.edu/documentation/tkperl/ Summary ~~~~~~~ Frame Used for grouping Tk::LabFrame Frame with border/label Tk::Pane Scrolled frame Adjuster Divides frames into resizable parts Scrolled Puts scrollbars on another widget Label One line of read-only text Message Multiple lines of read-only text Button You push it, stuff happens Checkbutton On or off Radiobutton Pick one at a time Menu Vertical menu with many options Menubutton Button designed to bring up a menu Optionmenu Button which brings up list of choices Tk::BrowseEntry Like above, but with current choice editable Scale Settable slider Tk::ProgressBar Read-only progress display Listbox Scrollable box containing a list of selectable items Entry Single-line text entry Text Multiple-line, complex text entry/display Tk::ROText Text without bindings to edit it Scrollbar Usable in conjunction with other things to scroll Canvas The swiss army widget Tk::NoteBook Selectable tabbed pages Tk::Table Table of widgets Tk::Tiler Table of widgets (how are these different?) Tk::Balloon Balloon help TK::Dialog Very simple popup dialog messageBox Even simpler one-shot popup dialog Tk::DialogBox Slightly more configurable popup dialog Tk::FileSelect Popup pre-made file selector Find headings by searching for the desired string at the end of a line, such as with "/Table$" in less. Geometry Managers ~~~~~~~~~~~~~~~~~ pack ~~~~ $slavewidget->pack(options) -after => $otherwidget -anchor => center|n|nw|w|sw|s|se|e|ne -before => $otherwidget -expand => 0|1 -fill => none | x | y | both -in => $masterwidget -ipadx => internal padding (default 0) -ipady => internal padding (default 0) -padx => external padding (default 0) -pady => external padding (default 0) -side => top | bottom | left | right $slavewidget->packForget() remove slave from management by packer $slavewidget->packInfo() returns info, of which first option set will be (-in => $master) $masterwidget->packPropagate( 1 | 0 | null ) enable or disable propagation, or query with null argument $masterwidget->packSlaves return list of packed slaves grid ~~~~ This places widgets in automatically-resized rows and columns. $leftmostslave->grid($slave2, $slave3, ...options) Tk::grid($slave1, $slave2, ...) -column => # (starts at 0) -columspan => # (default 1) -row => # -rowspan => # -in => $masterwidget -sticky => combination of n,s,e,w -ipadx, -ipady, -padx, -pady: as in pack -sticky performs the task performed by a combination of -anchor and -fill in the pack window manager. A string with certain special characters can also be used where the slave names would go: - extend widget in cell left of here to here ^ extend widget in cell above here to here x leaves an empty cell These make *way* more sense with the non-object-oriented syntax. See p.354 of the Welch book. The slaves given in one command are all in the same row. I recommend the non-object-oriented version; it is cleaner, and is also the only way to specify one of the special letters as the first slave. $slave->gridForget($more_slaves,...) Unmanage slave widget, forget properties $slave->gridRemove($more_slaves,...) Unmanage, but remember properties for later $master->gridColumnconfigure(index, options) $master->gridRowconfigure(index, options) set -minsize, -weight, and -pad options for column or row -weight indicates the relative amount assigned to each column/row when the master grows. Default 0 means no growth at all. $master->gridBbox() $master->gridBbox(col1, row1) $master->gridBbox(col1, row1, col2, row2) Return bounding box in pixels of given region $master->gridLocation(x,y) Returns (column, row) for given pixel; -1 for outside grid $master->gridSize() Return size as (colunns,rows) $master->gridInfo() List of elements in grid. First two items are (-in => $master). $master->gridSlaves(options) Return all slaves, or those in a particular row or column is give with -row or -column $master->gridPropagate(boolean) If false, the grid does not attempt to resize the master There does not appear to be any way to set a default -weight; it has to be set for each row and column individually. It is possible to include multiple widgets in the same cell with explicit row and columns. place ~~~~~ Place puts things at a fixed, specified location, either absolute or relative to other things. $widget->place(options) -in place relative to this widget, a parent or sibling -anchor center | n | nw... Place this point of slave -x, -y Absolute x,y offset to point given as anchor -relx, -rely Relative offset, added to above. From 0 to 1. -width, -height Absolute width and height -relwidth, .. Relative width/height, added to above -bordermode inside | outside | ignore Widts and heights can be negative, so you can make something slightly *smaller* than its parent in addition to larger. bordermode controls whether to consider the size and location of the master as the inside or outside of its border. $widget->placeForget unmap $widget->placeInfo Current configuration of widget, as option/value pairs. $master->placeSlaves List of children placed in master The placer does not attempt to manipulate the size of the master in any way. You must do this yourself. form ~~~~ ... see Tk::form Widgets ~~~~~~~ Names and Classes ~~~~~~~~~~~~~~~~~ By default, widgets are named .typeN, where type is the type of the widget and N increments as you create each one (starting at blank, then going to 1). To give a widget another name, use the Name option in its creation. This option is nonstandard in that it has a capital letter and no dash. To specify the class, use the -class option. The class, by default, is Type. If you change the name, the class does NOT automatically change with it to a capitalized version of the new name. $widget->widgetClass(Name=>name, -class=>class) Change Name and -class options after widget is created $widget->PathName() Return pathname to widget, as .foo.bar.baz (no toplevel name) $widget->optionAdd(pattern=>value, optional_priority) Add option to database. Pattern is exactly like in .Xdefaults $widget->optionClear() Resets all options $widget->optionGet(name, class) gets the relevant resource of the specified name OR class for the widget in question. If both are defined, the class overrides. Either can be left blank to match only the other. $widget->optionReadfile(filename, optional_priority) Reads in files such as .Xdefault at given priority Priorities: 20 widgetDefault hard coded defaults 40 startupFile application-specific startupfile defaults 60 userDefault user-specific startup files, Xserver, etc. 80 interactive default for any of the commands above General Options ~~~~~~~~~~~~~~~ name (option is Name, not -name) class anchor Anchor n | ne | ... how info aligned in widget background Background background color (switch alias -bg) foreground Foreground foreground color (alias -fg) borderWidth BorderWidth nonnegative 3D border (alias -bd) font Font font to use in widget Fonts can be specified in XLFD form (even for non-X platforms!) or as "font size style". Negative size is pixels; positive is points (see Tk::Font). Style is optional. relief Relief raised | sunken | flat | ridge | solid | groove jump Jump 1 | 0 - update only on button release justify Justify left | center | right text Text text to display testVariable Variable alternative to fixed text takeFocus TakeFocus null | 0 | 1 (see manpage) cursor Cursor use a named cursor or file There are lots of builtin cursors; see p545 of Welch's book or http://tronche.com/gui/x/xlib/appendix/b/ http://www.consistent.org/terran/tk/xcursor.png for custom, use '@cursor.xbm mask.xbm fgcol bgcol' Colors ~~~~~~ Prefixes: NULL Normal, active things highlight... The edges used in 3D reliefs. background is for inactive items, and color is for the active one. active... The thing the mouse is hovering over disabledForeground For disabled things. Foreground only. Empty string means normal color but stippled. select... Selected text. Unused for things other than text. insert... Things under insertion cursor troughColor The sunken area in scrollbars and scales notes: The color of a 3d relief cannot be independently set, but is instead automatically calculated by lightening and darkening the background. Functions to query ~~~~~~~~~~~~~~~~~~ @list=$widget->configure('-option') @listoflists=$widget->configure; $value=$widget->cget('-option') $widget->appname(optional_newname) get/set application name $widget->name() $widget->class() Returns name or class of widget $widget->containing(rootx, rooty) Returns window containing point given by x,y relative to root win $widget->parent() Return window's parent $widget->children() Returns a list of children, in stacking order $widget->width() $widget->height() Query width and height $widget->id() X window identifier or other OS equivalent $widget->pointerx() $widget->pointery() $widget->pointerxy() Return coordinates of the mouse, if on same screen as widget $widget->x() $widget->y() Return the x,y coordinates of window's upper-left border, relative to its parent $widget->rootx() $widget->rooty() Return the x,y coordinates of window's upper-left border, relative to the root window Functions to Manipulate ~~~~~~~~~~~~~~~~~~~~~~~ $widget->configure(-option => 'value', ...) $widget->bell() beepy beepy $widget->destroy() Destroys the widget $widget->raise(optional_abovethis) $widget->lower(optional_belowthis) Raise or lower the widget $widget->idletasks() Run any idle tasks, but don't process new events $widget->update() Process events and idle tasks $widget->OnDestroy(callback) Set a callback for window destruction $widget->Busy(-recurse => 0|1, -cursor => name) Recurse defaults to 0; cursor defaults to "watch". Adds Busy bindtag, grabs, etc. $widget->Unbusy() Undoes effects of above Other Functions ~~~~~~~~~~~~~~~ $widget->waitVariable(\$var) $widget->waitVisible $widget->waitWindow Runs the mainloop until the desired condition is met. visibility waits for a widget to be visible (such as waiting for a created window to show up); window waits for it to be destroyed. Calls to wait cannot be nested. Toplevel/MainWindow ~~~~~~~~~~~~~~~~~~~ container Container 0|1 - contains another application menu Menu $menu to be used as menubar -screen X screen - option form only use Use hex id of window title Title string for title bar Frame ~~~~~ container Container as toplevel use Use ? height Height width Width Note that -borderwidth defaults to 0 for a frames, so unless you manually set it higher, the -relief option will have no effect. Button ~~~~~~ $button->flash blinky blinky $button->invoke as if pushed text Text to display command Command callback when button 1 released state State normal | active | disabled default Default normal | active | disabled Checkbutton ~~~~~~~~~~~ Methods: flash, invoke, select, deselect, toggle text Text to display command Command callback when button 1 released variable Variable variable holding state offValue Value value in variable when off onValue Value value in variable when on state State normal | active | disabled indicatorOn IndicatorOn Radiobutton ~~~~~~~~~~~ Methods: flash, invoke, select, deselect text Text to display command Command callback when button 1 released variable Variable variable holding state value Value variable's value for this button state State normal | active | disabled indicatorOn IndicatorOn Radio buttons referring to the same variable will behave as a group, because they will deselect themselves when the variable changes. Menu ~~~~ title Title menu title postCommand Command callback before menu posted tearOff TearOff 1 | 0, for tearoff allowed or not tearOffCommand TearOffCommand callback, args "menu tearoff" type Type normal | menubar | tearoff $menu->add(type, options) cascade checkbutton command radiobutton separator -accelerator => value -underline => index to character to underline -columnbreak => 0 | 1 -command => callback -indicatoron => 0 | 1 (for check/radio only) -label => the text that appears -menu => submenu pathname (for cascades only) -offvalue => for checkbutton (also -onvalue) -state => normal | active | disabled -value => for radiobutton -variable => for radio and checkbutton $menu->activate(index) Activates the indicated item $menu->clone($parent, optional_clonetype) Clones $menu as child of $parent. Type is normal | menubar | tearoff $menu->delete(index1, optional_index2) Delete all items between the indices, inclusive $menu->entryconfigure(index, options...) Reconfigure the options for a menu component $menu->index(index) returns numerical index corresponding to the index given $menu->insert(index, type, options) like add, but inserts in other place $menu->invoke(index) as if pushed $menu->post(x,y) $menu->unpost Display the menu at given location, or undisplay it $menu->postcascade(index) Post submenu associated with given cascade entry $menu->type(index) return type of item at index $menu->yposition(index) return y-coordinate of the topmost pixel in the given entry Index arguments to indicate which menu item: # 0 is first item active item which is currently active end,last last item none none (use with, say, activate) @number y-coordinate within menu pattern match against label It is NOT POSSIBLE to use the resource database to specify properties for individual menu entries at this time. This is a known problem. Menubutton ~~~~~~~~~~ This is a special button designed to bring up a menu more easily than doing it with custom bindings on a normal button. text Text Label on button direction Direction above|below|left|right|flush menu MenuName menu (must be child of button!) state State normal | active | disabled indicatorOn IndicatorOn ? Label ~~~~~ A label provides read-only text, broken on newlines. text Text text to display textVariable TextVariable variable holding text to display use one of text or textvariable. Message ~~~~~~~ A message provides multiple lines of readonly text, automatically flowed. text Text text to display textVariable TextVariable variable holding text to display aspect Aspect width/height*100 (def 150) justify Justify left | center | right Scale ~~~~~ orient Orient horizontal | vertical bigIncrement BigIncrement size of large increments (0=10%) command Command invoked on change; arg new value digits Digits # significant digits from From value at left/top end of scale to To value at right/bottom end of scale length Length length/width in pixels sliderLength SliderLength length/width of slider sliderRelief SliderRelief raised | sunken tickInterval TickInterval ticks at this interval (none if 0) showValue ShowValue 1 | 0 (show setting as text) resolution Resolution round to multiples of this if nonzero label Label label to show variable Variable variable to hold value $scale->coords(optional_value) Get (x,y) of current or specified location $scale->get(opt_x, opt_y) Get value given x,y location - one of x or y is ignored $scale->identify(x,y) Returns (slider | trough1 | trough2) indicating what's at the specified point $scale->set(value) Sets scale to given value Listbox ~~~~~~~ A listbox is a list of items from which you can select. Entry ~~~~~ An entry is a single-line text entry box textvariable TextVariable reference to variable holding text width Width width in characters (default 20) show Show show all this character (*, etc) validate Validate none | focus | focusin | focusout | key | all validateCommand ValidateCommand command to run to validate invalidcommand InvalidCommand command to run when validation fails The arguments to the validate commands are: Proposed new value characters added/deleted old value index of addition/deletion type of action (1 INSERT, 0 DELETE, -1 other) Text ~~~~ spacing1 Spacing1 Extra space above each paragraph spacing2 Spacing2 Extra space between each line spacing3 Spacing3 Extra space below each paragraph tabs Tabs list of tab stops, can be followed by left|right|center|numeric wrap Wrap none | char | word state State normal | disabled There are several ways of indexing into the text: line.char (lines start at 1, chars at 0) @x,y end named mark .first .last + chars (or -) + lines linestart, lineend wordstart, wordend Tags can have their own fonts, colors, etc: -background, -foregrond, -bgstipple, -fgstipple, -borderwidth, -font, -justify, -lmargin1, -lmargin2, -offset, -overstrike, -relief, -rmargin, -spacing[1-3], -state, -tabs, -underline, -wrap, -elide, -data Marks refer to a single zero-width place, unlike tags which have size. They have left or right gravity. $text->bbox(index) Returns x, y, width, height for character given by index $text->delete(index1, optional_index2) Delete between index1 and index2, or single char at index1 $text->dump(optional_options, index1, optional_index2) Dumps key/value/index triplets. Keys are text, mark, tagon, and tagoff. Switches: -all, -command, -mark, -tag, -text, -window $text->get(index1, optional_index2) Return the characters in range. $text->index(index) Converts index to line.char form $text->insert(index, chars, optional_taglist, optional_chars, ...) Inserts characters immediately before index. Taglist contains tags for the characters; if not specified, they inherit from their position. $text->mark.... not done $text->search $text->xview() Returns a list of 0 to 1 fractions indicating left and right $text->xviewMoveto(fraction) Adjusts left fraction $text->xviewScroll(number, what) Shifts the view left or right. what is units | pages. $text->yview... Identical commands to the xview versions. $text->yview(?-pickplace?, index) Makes index visible. Always at top without -pickplace, other places with. Scrollbar ~~~~~~~~~ command Command callback to widget ([$widget => 'xview']) width Width narrow scrollbar dimension orient Orient horizontal | vertical elements: arrow1, trough1, slider, trough2, arrow2 $scroll->activate(optional_element) can take arro1, slider, or arrow2 returns current active with null $scroll->delta(deltaX, deltaY) Uses only one of two, depending on direction Returns logical change corresponding to given pixel movement $scroll->fraction(x, y) Returns setting for given pixel $scroll->identify(x, y) Returns element at given pixel $scroll->set(first, last) This is called by the widget. first and last are from 0 to 1. To set up a scrollbar, you put this for the scrollbar command: -command => [$widget, 'xview'] and this in the widget: -xscrollcommand => [$scroll, 'set'] Canvas ~~~~~~ scrollRegion ScrollRegion left, top, right, bot coords confine Confine actually restrict to above? state State normal | disabled | hidden xScrollIncrement ScrollIncrement jump for x scrolling (same for y) $canv->addtag(tag, searchspec, args) searchspecs: all above tagorid below tagorid closest x y enclosed x1 y1 x2 y2 overlapping x1 y1 x2 y2 withtag tagorid $canv->delete(list of tags or IDs) delete items $canv->dtag(tag or id, tag to delete) If tag to delete is blank, it defaults to the first arg $canv->itemcget(tag or id, option) returns option $canv->itemconfigure(tag or id, option, value, ...) Configures item $canv->postscript(options) Postscript returned unless -file given see manpage for other options $canv->bind(tagorid, sequence, callback) bind for canvas item $canv->createArc(x1, y1, x2, y2, options) $canv->createBitmap(x, y, options) $canv->createGrid(x1, y1, x2, y2, options) $canv->createImage(x, y, options) $canv->createLine(x1, y1, ..., xn, yn, options) $canv->createOval(x1, y1, x2, y2, options) $canv->createRectangle(x1, y1, x2, y2, options) $canv->createText(x, y, options) $canv->createWindow(x, y, options) Patterns: [on, off, on, off, etc.] '.,-_ ' where: . is 2 on , is 4 on - is 6 on _ is ??? space after each is normally 4, doubled with a space char Tags: all and current are special combine with &&, ||, ^, ! operators Addon Widgets ~~~~~~~~~~~~~ These are part of Perl/Tk, but not part of the Tk default widget set. The ones listed as Tk::Foo must be explicitly included. Some of these come from Tix; some are Perl/Tk innovations. mega ~~~~ This is complex interface for creating composite widgets. I won't go into it in detail here, but it's used by some of the widgets below. $handle = $widget->Subwidget("name"); get handle to named subwidget Scrolled ~~~~~~~~ This is a wrapper which automatically adds scrolling to widget. $whatever = $window->Scrolled('widget', -scrollbars => where) Create scrolled widget. -scrollbars can be omitted, or n,nw,w, etc. The letter "o" preceding one of the others indicates that the bar appears only when needed. named subwidgets: scrolled, xscrollbar, yscrollbar, corner Tk::Pane ~~~~~~~~ Scrollable frame. Doesn't include the scrollbars itself; provides the [xy]view functions to interface with them. -sticky direction(n|e|w|s) plus optional 'o' as in Scrolled after the style of the grid geometry manager -gridded x|y|xy - snap to cell; used only if managed by grid $pane->see($widget, options) Move so listed widget is displayed -anchor align widget in given place. "center" unavailable. $pane->xview(...) $pane->yview(...) These behave as for a Text widget. See description there. Optionmenu ~~~~~~~~~~ A button displays the currently selected item; when you click on it, you get a list to pick an option. -options As addOptions, but in array ref -variable stores current choice -textvariable read/write version of above (undocumented) -command callback $opt->addOptions(optionlist); each option is: $val [$label => $val] Tk::ROText ~~~~~~~~~~ A text widget with bindings removed, so it is read only. See the Text widget for information. Tk::ReindexedText ~~~~~~~~~~~~~~~~~ A text widget with the line number of the first line changeable from 1. There is also a ReindexedROText. lineStart LineStart default 1 toIndexCmd ToIndexCmd callbacks to translate user to "native text" fromIndexCmd FromIndexCmd translate other way Tk::TextUndo ~~~~~~~~~~~~ A text widget with undo capabilities. New methods: $text->Load($filename); $text->Save($filename); uses loaded or set filename if none specified $text->FileName($filename); The default undo binding is: Event <> Tk::ProgressBar ~~~~~~~~~~~~~~~ Options: -width, -length, -from (default 0), -to (def 100) -blocks => number of segments -gap => pixels between blocks (default 1) -resolution => round displayed value to this (default 1) -anchor => w | e... sets start side AND DIRECTION -colors => [ #, 'color', #, 'color, ... ] display given color after given percentage -variable, -value current value, either a variable or constant $bar->value(value) set/query value Tk::BrowseEntry ~~~~~~~~~~~~~~~ This is a more limited version of Tix's ComboBox, apparently. It's basically an Entry with a popup menu of options as well as the ability to type. -label unused (or buggy such that it doesn't do anything) -variable \$scalar -listwidth -browsecmd function gets widget and text when selection made -listcmd called when list popped up -arrowimage on the popup button -choices list of choices (array ref) -state normal | readonly | disabled $be->insert(index, string) Inserts choice at index (such as "end", or number) $be->delete(index1, index2) deletes between indices Adjuster ~~~~~~~~ Pack this into a frame with other widgets, and it lets you control how much space each side gets. side Side which side is managed? top|bottom|left|right widget Widget widget which is managed $adj->packAfter($managed_widget) Convenience function to set widget and side, and pack with appropriate -fill values. $adj->packForget(boolean) also unpack managed widget if given true arg $adj->slave() Returns managed widget More limited version: $widget->packAdjust() Saves separate creation call, but you can't set all the options, and you can't get a handle to the adjuster itself. Tk::LabFrame ~~~~~~~~~~~~ A frame with a label. Options in addition to normal frame are: -label 'text' -labelside top | bottom | left | right | acrosstop acrosstop draws a "groove" around the frame and puts the label in the groove on the top. It looks neat. For reasons I don't understand, the grid geometry manager does not work correctly inside a LabFrame. You must put a normal Frame inside the LabFrame, or cells will not fill and expand correctly. Tk::Table ~~~~~~~~~ options: -rows => #, -columns => #, -scrollbars => 'anchor', -fixedrows => #, -fixedcolumns => #, -takefocus => bool Create widgets with table as parent. Position with: $table->put($row, $col, $widget) All configuration options for a Frame also available Limitations: o Very large Tables consume a lot of X windows o No equivalent of pack's -anchor/-pad etc. options Tk::Tiler ~~~~~~~~~ Scrollable frame containing many subwidgets $tl=$window->Scrolled('Tiler', -columns => n, -rows => m) Create a tiler $foo = $tl->whatever Create widget within tiler $tl->Manage($foo,...) Manage child widgets in tiler Tk::NoteBook ~~~~~~~~~~~~ Tabbed pages ocupying same space $w = $window->NoteBook(); Create notebook $page1 = $w->add("pageN", options); Add another tabbed page delete(pagename) Removes a page pagecget(pagename, -option) pageconfigure(pagename, options) Configure a page raise(pagename) Raise page raised() Returns name of currently raised page options: -anchor center|n|nw|w|... -bitmap, -image, -label text on tab -justify for text on tab label -wraplength for text on tab label -createcmd callback when page first displayed -raisecmd callback each time page displayed -state normal | disabled Tk::Animation ~~~~~~~~~~~~~ Displays sequence of Photos, or do automatically from animated gif. $img = $widget->Animation(-format => 'gif', -file => 'foo.gif'); $img->start_animation(period_of_repeat) $img->stop_animation(period_of_repeat) $img->add_frames(@images) Tk::HList ~~~~~~~~~ This is a heirarchical list, for things like directory trees. browsecmd Browsecmd callback when user "browses" command Command callback on doubleclick or return columns Columns how many of 'em? drawBranch DrawBranch 1|0 - draw branch lines? header Header 1|0 - ? indent Indent amount of indent separator Separator default "." - interpret this char as sep indicatorCmd IndicatorCmd itemType ItemType $hlist->add($entrypath, options) -at position index (0 is first, etc) -after, -before insert relative to the given entry -data for programmer's use; query with info method -itemtype 'text', 'imagetext', etc. -state normal | disabled $hlist->addchild($parentpath, options) As above, but path is to parent instead of widget $hlist->delete(option, $entrypath) -all all entries in HList, path not required -entry listed entry and any children -offsprings delete children only, not given item -siblings delete siblings only, not given item $hlist->itemCreate($entrypath, col, options) options are -itemtype, option-specific items $hlist->itemDelete($entrypath, col) Delete given entry in given column $hlist->itemExists($entrypath, col) Returns true if item exists $hlist->itemCget($entrypath, col, option) $hlist->itemConfigure($entrypath, col, options) The usual configuration options The whole addFoo and itemFoo commands are confusing. With only one column, the itemFoo methods can be IGNORED. With multiple columns, you must add entries with addFoo, and then create the actual display item with the itemFoo functions. See Tk::HList for more. Tk::Tree ~~~~~~~~~ Derived from HList. ... Tk::DirTree ~~~~~~~~~ Derived from Tree. ... TK::TList ~~~~~~~~~ Tix Tabular List. ... Tk::TixGrid ~~~~~~~~~~~ This is buggy, and is now also deprecated. Tk::InputO ~~~~~~~~~~ Blank widget of some sort that exists only to take bindings. ...? Addon Non-Widgets ~~~~~~~~~~~~~~~~~ These are not actually widgets, but are used in some way with the widgets. Tk::Balloon ~~~~~~~~~~~ For easy balloon help $bal = $top->Balloon(-statusbar => $statusbarwidget); Create a balloon. Accepts all options for a Frame, plus: -initwait before display in ms; default 350 -statusbar widget to display status message (Label,etc) -state balloon | status | both | none -balloonposition widget | mouse -postcommand CODE ref executed on popup - return false to preclude popup. Return "X,Y" for pos. -cancelcommand as above, for un-popping it -motioncommand executed on motion; return true to unpopup $bal->attach($widget, options); -statusmsg message for status bar. Will dereference scalar ref -balloonmsg message for balloon, as above -msg Used for both of above if they rae not given Can also give one of the general Balloon options to override. -msg will also take an array ref for per-item help in menus, or a hash-ref for per-item help in canvases. -balloonmsg won't! $bal->detach(widget) detaches a widget from the help system $bal->destroy destroys specified balloon It is better to use one balloon attached to as many widgets as possible instead of one balloon per widget, from a performance point of view. Tk::DItem ~~~~~~~~~ This is NOT A WIDGET, but a general type used in several widgets. It is from Tix. Each item has individual options and a reference to a Display Style, sort of like HTML stylesheets. There are three types of DItem - text, imagetext, and window. Text ~~~~ textStyle -style reference to an ItemStyle text -text the text itself underline -underline index to underline Imagetext ~~~~~~~~~ ... Window ~~~~~~ ... $style = $widget->ItemStyle('type', options); Create an itemstyle type is 'text', 'imagetext', etc. options are -stylename, -refwindow, options for style Tk::WinPhoto ~~~~~~~~~~~~ Screen shot. $image=$mw->Photo(-format => 'Window', -data => oct($mw->id)); can then use $image->write. Tk::Compound ~~~~~~~~~~~~ makes multi-line compound images. Makes an image out of anything (text, etc.) Use for something like displaying text AND a bitmap in a button. ... Widgets in New Windows ~~~~~~~~~~~~~~~~~~~~~~ Tk::Dialog ~~~~~~~~~~ pre-made modal dialogs for your convenience. $dialog=$mw->Dialog(options) -title, -text, -bitmap, -default_button, -buttons $dialog->Show(); can take -global option to grab globally. Returns value of button pressed The bitmap is one of the default builtins, or an @-preceded filename to a file output by the bitmap utility. It is not possible to register an external bitmap as a name; you must refer to it by filename. Also, you cannot use a previously-registered Bitmap, because they are specific to a mainwindow. Builtins are: error, gray25, gray50, hourglass, info, question, questhead, warning messageBox ~~~~~~~~~~ A one-shot simple Dialog which is created and run in one step. This is somewhat less flexible than Dialog, in that the choice of buttons is limited to a small number of popular presets. $widget->messageBox(options); -default 'name of default button' -icon as in Dialog -message Message to display -title Title for window -type AbortRetryIgnore | OK | OKCancel | RetryCancel | YesNo | YesNoCancel Tk::DialogBox ~~~~~~~~~~~~~ Slightly more flexible version of above. Has a "top" and "bottom" part, the former of which displays arbitrary widgets and the bottom of which displays the row of buttons. Returns name of chosen button. $dialogbox=$mw->DialogBox(options) -title, -buttons, -default_button $dialogbox->add(widgetname, options) Add any widget, giving it options as usual. There is no way to remove it again. Must use geometry manager manually, as usual. $dialogbox->Show() Run it. Can specify grabtype as argument (default is local). chooseColor ~~~~~~~~~~~ Created and run in one step: $widget->chooseColor(options) options: -initialcolor, -title Returns color as hex string "#RRRRGGGGBBBB". Note that the "Hue" scroller in the HSB colorspace seems a bit buggy. Tk::ColorEditor ~~~~~~~~~~~~~~~ This automatically recolorizes widgets. The actual dialog is almost identical to chooseColor's. $col=$mw->ColorEditor(options) options: -title-cursor, -display_status, -add_menu_item, -delete_menu_item -widgets Arrayref of widgets to apply to $col->Show() Runs $col->delete_widgets(widgets) This is the only way to remove widgets - if you call configure with a new list, it is ADDED to the current ones Note that $widget->Descendants(), to get all descendants of a widget, is quite useful here. getOpenFile ~~~~~~~~~~~ Also getSaveFile. Based on TK::FBox. It is created and run in one step: $filename = $widget->getOpenFile(options) $filename is blank if "cancel" was pressed. -defaultextension -filetypes -initialdir -initialfile -title File patterns: typeName [extension ... ] [macType ... ] The mactypes are optional. Tk::FileSelect ~~~~~~~~~~~~~~ Automatic file select dialog box. Poor documentation; see http://www.perlmonth.com/columns/perl_tk/perl_tk.html?issue=9&print=1 -directory => initial directory -initialfile => file -filter => shell glob -verify => [perl test, perl test, etc] $file = $fs->Show(); If you want FileSelect to be used for getOpenFile, etc., say: use Tk::FileSelect 'as_default' Images ~~~~~~ Images are not directly placed in windows, but are used with things like buttons, often as an argument to an option like -image. $widget->(options) Creates image. Use the returned handle as the argument. $widget->imageTypes Returns list of valid types $image->delete() Deletes image $image->height() $image->width() Returns height, width $image->imageNames Returns all known images for same mainwindow $image->type Returns type of image $image->configure $image->cget Set individual image options Note that image options DO NOT HAVE resource equivalents. Bitmap ~~~~~~ Must be in in .xbm format, from the "bitmap" program. options: -background (empty means ignore mask and all bg is transparent) -foreground -data | -datafile -maskdata | -maskfile Pixmap ~~~~~~ Must be in .xpm format, from the "pixmap" program. options: -data, -file Photo ~~~~~ Supports GIF, PPM, and PGM formats. options: -data | -file -format -gamma (default 1) -height, -width -palette ("numgreys" or "numred/numgreen/numblue") There are many methods available; see Tk::Photo. Callbacks ~~~~~~~~~ Without Arguments: ... = \&subname ... = sub { ... } ... = 'methodname' ... = [ $object => 'methodname' ] ... = [ methodname => $object ] With Arguments: ... = [ \&subname, args ] ... = [ sub {...}, args ] ... = [ 'methodname', args ] In callbacks bound to a key, one of the arguments can be an Ev(...) call. Ev CANNOT BE USED with other types of callbacks. There are two largely unrelated ways it can be used. If the argument is an array reference, it will perform a second "nested' callback, which can be used to perform additional member functions. The syntax is exactly like the main callback, above, except that everything must have [ ] around it. If its argument is a single scalar, it is expanded into an argument to the callback it is in, based on the letter: Configure |Button ||Key |||Motion ||||Expose |||||eNter/Leave ||||||Focus |||||||ciRculate ||||||||Visibility |||||||||maP/unmap |||||||||| # CBKMENFRVP Number of last client request (serial) a C......... above b .B........ button number c ....E..... count d .....NF... detail (string of form NotifyFoo) f .....N.... focus (0 or 1) h C...E..... height k ..K....... keycode m .....NF... mode (string of form NotifyFoo) p .......R.. place (PlaceOnTop or PlaceOnBottom) s .BKM.N.... state (decimal string) s ........V. state (Visibility@Obscured; @ is Un|Partially|Fully) w C...E..... width A ..K....... ASCII character B C......... border_width E CBKMENFRVP send_event field K ..K....... keysym, as textual string N ..K....... keysym, as decimal number T CBKMENFRVP type W CBKMENFRVP window, as perl/Tk object ($widget) X .BKM...... x_root Y .BKM...... y_root Others valid for only certain types of event: t: time x: x y: y @: "@x,y" R: root window S: subwindow returning from a callback causes the next matching callback to execute. Tk->break terminates the lot. Bindings and Events ~~~~~~~~~~~~~~~~~~~ $widget->bind(NULL | tag | sequence | tag,sequence) gets bindings $widget->bind(sequence,callback | tag,sequence,callback) sets bindings $widget->eventAdd('<>', sequence, optional_sequence...) Add a new virtual event, in addition to any existing for same name $widget->eventDelete('<>', optional_sequence,...) Delete event; delete all of same name if no sequence given $widget->eventInfo('<>') return info on virtual event listed, or all if no argument $widget->eventGenerate(event, options=>value, ...) Generate event. Se Tk::event for options. A tag can be: an internal window name a toplevel window name a widget class, like Tk::Button, returned by `ref $widget` "all" an arbitrary tag added with bindtags() An event is of the form A virtual event is of the form <> Event Modifiers: Control Shift Lock Meta, M Alt Button#, B# (# from 1 to 5) Mod#, M# (# from 1 to 5) Double Triple Event Types with Detail Type: ButtonPress, Button button number ButtonRelease button number FocusIn FocusOut Motion KeyPress, Key X keysym KeyRelease X keysym Enter Leave Expose Map Unmap (plus less common ones; see Tk::bind) Special Callbacks ~~~~~~~~~~~~~~~~~~ After ~~~~~ These run from the event loop. $widget->after(ms) sleep for specified time in ms $id = $widget->after(ms, callback) Execute callback after ms milliseconds $id = $widget->repeat(ms, callback) Execute callback repeatedly after ms milliseconds $widget->afterCancel($id) or $id->cancel() Cancels callback if it hasn't already run $widget->afterIdle(callback) Runs callback when the event loop is next idle $widget->afterInfo() Returns list of identifiers $widget->afterInfo($id) Returns list with callback and either "idle" or "timer" Fileevent ~~~~~~~~~ $widget->fileevent(Handle, readable, optional_callback) $widget->fileevent(Handle, writable, optional_callback) Works best with nonblocking IO. Without a callback, queries current callback. With an empty string, removes existing callback. There can be only one handler each for readable and writable for a given file. Utilities ~~~~~~~~~ focus ~~~~~ Utilities to move focus within a toplevel $widget->focus focus widget in question $widget->focusCurrent Return the currently focused window $widget->focusLast Most recent window to have had focus $widget->focusNext $widget->focusPrev As expected. Used with keyboard bindings. $widget->focusFollowsMouse Move focus with mouse $widget->focusForce Focus widget in question even if this toplevel isn't focused by the windowmanager. This grabs the focus and is rude. Note that canvases have an internal focus, so you have to call $canvas->Tk::focus. The other functions are ok. Font ~~~~ $font->actual(-options) $widget->fontActual(font, -options) Returns information about actual font attributes, as an array of -options and arguments. Options are -family, -size, -weight, -slant, -underline, -overstrike $font->configure(options) Query or modify attributes for fonts $font = $widget->Font(options) $font = $widget->fontCreate('optional_name', options) Create a new font and return reference. With no name given, one of the form font# will be provided for you. Fonts are shared amongst children of the same mainwindow. $font->delete $widget->fontDelete(fontnames) Unlink specified named font. $widget->fontFamilies Return list of all font families available on $widget's display. $widget->fontNames Return list of all font names currently in existence $font->measure('text') $widget->fontMeasure(font, 'text') Returns the size of 'text' in given font. Returns total width; tabs are not expanded. Height information is not returned. $font->metrics(options) $font->fontMetrics(font, options) With no options, returns an array of options and values. With an option, returns only that option. Options are -ascent, -descent, -linespace, and -fixed. The options are described in detail in Tk::Font. Tk::X11Font ~~~~~~~~~~~ $font = $widget->X11Font(options) options are: foundry => 'foo' family => 'bar' point => 'baz' etc. $font = $widget->X11Font('*-normal-x--font-string-*') $font->Property methods exist, to set a property, for: Foundry, Family, Weight, Slant, Swidth, Adstyle, Pixel, Point, Xres, Yres, Space, Avgwidth, Registry, Encoding when $font is used a scalar context, it returns the first matching entry. Selection ~~~~~~~~~ Note that the man page is Tk::selection, not Tk::Selection as expected. This is an interface to the X selection mechanism, as described in the X Inter-Client Communication Conventions Manual. (http://tronche.com/gui/x/icccm/) $widget->SelectionClear(-selection => 'name') Clear selection. Name is from ICCCM, such as 'PRIMARY' or 'CLIPBOARD'. 'PRIMARY' is the default if unspecified. $widget->SelectionGet(-selection => 'name', -type => 'type') Selection is as above. Type also comes from the ICCCM, and is something like 'STRING' or 'FILE_NAME'. The default is 'STRING'. Support for types other than 'STRING' is questionable and undocumented. Type 'TARGETS' returns a list of other types. $widget->selectionHandle(-selection => 'name', -type => 'type', -format => 'format', callback) Create handler for selection requests, to be called whenever $widget owns a selection and somebody tries to get it as the given type. Type and format default to STRING. The callback is passed an offset and maxbytes as arguments, and must return the data accordingly. If callback dies, the program behaves as if the selection did not exist. $widget->selectionOwner(-selection => 'name') Returns owner of the selection, or null if it's not anything in this application. $widget->selectionOwn(-selection => 'name', -command => 'callback') Take over selection. Callback, if given, is called when something *else* takes it over again. Clipboard ~~~~~~~~~ $widget->clipboardClear() Clear current contents $widget->clipboardAppend(options, data) -type, -format standard values from ICCCM. Common values for -type and -format are "STRING". You can use the "--" option to mark the end of options if your data happens to start with a -. Tk::DragDrop, DropSite ~~~~~~~~~~~~~~~~~~~~~~ The drag and drop functionality is disturbingly undocumented. see http://www.perltk.org/articles/Drag-and-Drop.htm The source is the thing you start dragging from; the site is its potential destination. The DND token is a label with text or an image. You can give it normal label options (colors, etc.) my $DNDtoken = $sourcewidget->DragDrop(options); -event Defaults to "" -sitetypes Array of strings. Default includes local. -cursor Default "hand2" -delta -handlers [[-type => "type", [callback]]] -type defaults to STRING -selection Default "XdndSelection". For Local, received as token. For all others, different meaning. -startcommand, -endcommand, -predropcommand, -postdropcommand All callbacks $destwidget->DropSite(options) -droptypes array of types it will accept, default none -entercommand, -leavecommand, -motioncommand, -dropcommand All there are pointers to callbacks which will receive a token, x, and y coordinate (in pixels) as arguments. Types: Local, XDND, Sun, KDE With XDND, you set up handlers for different data types with the -handlers option. The receiving site uses SelectionGet for "XdndSelection", and the handler for the appropriate type is called. Local is the same, except that you can specify any selection name you want with -selection, instead of being stuck with XdndSelection. The handlers are applied to whichever selection you specify. Local works only within the same application. The others are more general. With Local and Sun, the -selection can be set to any arbitrary string and it will be passed, with XDND and KDE it appears to have some other (or no) use. Wm ~~ Interaction with the windowmanager. $toplevel->aspect(minNumer, minDenom, maxNumer, maxDenom); Constrain resizing aspect ratio. Details not documented well in Tk::Wm. $toplevel->client(optional_name) query/set client (what is that?) $toplevel->command(optional_value) query/set command name of application $toplevel->title(title) query/set title $toplevel->transient($master) Inform WM this is a transient belonging to master, so it can maybe not decorate it or something $toplevel->wmGrid() $toplevel->wmGrid(basewidth, baseheight, widthinc, heightinc) Query or set gridding (increments in resizing) The increment options are obvious; the base options are the current size in grid units. The catch is that this will break if you haven't mapped the window yet, because it won't have the size you think it has. See also -setgrid option, which is given to something like a text widget to indicate that its fond should be used for the grid. $toplevel->geometry(optional_newvalue) set/query geometry, in pixel units unless gridded $toplevel->minsize(width, height) $toplevel->maxsize(width, height) set/query max/min sizes $toplevel->resizable(width_boolean, height_boolean) query/Set width/height resizability $toplevel->iconify $toplevel->deiconify duh $toplevel->withdraw unmaps. use deiconify to remap. $toplevel->state returns normal | iconic | icon | withdrawn $toplevel->iconbitmap(bitmap) $toplevel->iconmask(bitmap) $toplevel->iconimage(image) $toplevel->iconwindow($widget) $toplevel->iconname(name) $toplevel->iconposition(x,y) set/query properties of icon used by some windowmanagers See Tk::Wm for more. tixWm ~~~~~ A couple of extra Windowmanager functions: $toplevel->wmCapture Converts toplevel into a non-toplevel. It is unmapped, and has to be redisplayed somehow. $widget->wmRelease Make something into a toplevel widget, initially in "withdrawn" state. Apparently Perl support is somewhat sketchy for these. palette ~~~~~~~ Ways of modifying the color scheme. $widget->setPalette(backgroundcolor) Generate an entire color scheme by inferring everything from the specified main background color. $widget->setPalette(options) With this syntax, you specify multiple settings, and the rest are inferred. Settable settings are: foreground background activeForeground activeBackground selectColor selectForeground selectBackground highlightColor highlightBackground disabledForeground insertBackground troughColor It is important to note that you specify these as shown, in the option database format - with the upper case letter, and without the leading dash. Options are added at the 'widgetDefault' priority. Error ~~~~~ Way of processing background errors. *YOU* define Tk::Error, and it is called at appropriate times, with arguments: ($widget, $error, @locations) as if by: $mainwindow->Tk::Error("message', location, ...) Alternatively, use Tk::ErrorDialog for a stock solution. variables ~~~~~~~~~ $Tk::library Unused with perl (use @INC instead) $Tk::version $tk::patchLevel Unused with perl (use $Tk::VERSION) $Tk::strictMotif If set, act more like Motif $Tk::VERSION Version of Perl/tk as major.minor Misc Notes ~~~~~~~~~~ MainWindow constructor invokes Tk::CmdLine::SetArguments implicitly. Pixel arguments can use c, i, m, or p suffixes, for centimeters, inches, millimeters, or points. No suffix means pixels.