Listbox(3pm)
π Listbox β Tk::Listbox π
okay bestie, welcome to the glow-up guide for Tk::Listbox π
this is from the User Contributed Perl Documentation, section 3pm, and we're about to make a widget that creates and manipulates Listbox widgets. yes she's that girl.
β¨ SYNOPSIS β¨
$listbox = $parent->Listbox(?options?);
that's it. that's the whole entrance. she walks in, she's a listbox. periodt. π
π STANDARD OPTIONS π
these are the inherited basics, the family heirlooms, the ones she got from the standard Tk::options situation. no need to reinvent the wheel when the wheel is this cute:
-background-borderwidth-cursor-disabledforeground-exportselection-font-foreground-height-highlightbackground-highlightcolor-highlightthickness-offset-relief-selectbackground-selectborderwidth-selectforeground-setgrid-state-takefocus-tile-width-xscrollcommand-yscrollcommand
go peek at Tk::options if you want the full tea on what each of these standard options actually does π
πΈ WIDGET-SPECIFIC OPTIONS πΈ
these are her options, the ones that make her her. every single one gets its own little moment, because we don't skip anyone in this house.
-activestyle(Name:activeStyle, Class:ActiveStyle) β this is the lewk for the active element, and you've got exactly three choices, no free-styling:dotbox(draws a focus ring around the active element, very demure),none(no special indication of the active element at all, she's incognito), orunderline(underlines the active element). the default isunderline. β¨-height(Name:height, Class:Height) β how tall you want the window, measured in lines. and here's the cute part: if you set it to zero or less, the desired height is made just large enough to hold all the elements in the listbox. she'll size herself, she's adaptable π¦-listvariable(Name:listVariable, Class:Variable) β okay so heads up, the following is only partially implemented in Perl/Tk:
it specifies the reference of a variable. the value of that variable is an array that gets displayed inside the widget; if the variable value changes then the widget will automatically update itself to reflect the new value (self-updating queen π). attempts to assign a variable with an invalid list value to -listvariable will cause an error. and attempts to unset a variable that's in use as a -listvariable will fail, but will not generate an error. so it just... won't. quietly. noted. π
-selectmode(Name:selectMode, Class:SelectMode) β specifies one of several styles for manipulating the selection. the value of the option may be arbitrary, but the default bindings expect it to be eithersingle,browse,multiple, orextended. the default value isbrowse. π-state(Name:state, Class:State) β two states only, bestie:normalordisabled. if the listbox is disabled then items may not be inserted or deleted, items get drawn in the-disabledforegroundcolor, and selection cannot be modified and is not shown (though selection information is retained β she remembers everything, she's just not showing it π).-width(Name:width, Class:Width) β the desired width of the window, in characters. if the font doesn't have a uniform width then the width of the character0is used when translating from character units to screen units. if zero or less, then the desired width is made just large enough to hold all the elements in the listbox. matching energy with-height, we love consistency π
π DESCRIPTION π
the Listbox method creates a new window (given by the $widget argument) and makes it into a listbox widget. additional options, described above, may be specified on the command line or in the option database to configure aspects of the listbox such as its colors, font, text, and relief. the listbox command returns its $widget argument. and listen β at the time this command is invoked, there must not exist a window named $widget, but $widget's parent must exist. rules are rules, no cap.
a listbox is a widget that displays a list of strings, one per line. when first created, a new listbox has no elements β a blank slate, an empty canvas, main character energy before the plot starts. elements may be added or deleted using methods described below. in addition, one or more elements may be selected as described below. if a listbox is exporting its selection (see exportSelection option), then it will observe the standard X11 protocols for handling the selection. listbox selections are available as type STRING; the value of the selection will be the text of the selected elements, with newlines separating the elements.
it is not necessary for all the elements to be displayed in the listbox window at once; commands described below may be used to change the view in the window. listboxes allow scrolling in both directions using the standard xScrollCommand and yScrollCommand options. they also support scanning, as described below. π₯
π¦ INDICES π¦
lots of the methods for listboxes take one or more indices as arguments. an index specifies a particular element of the listbox, and you can do it any of these ways:
- number β specifies the element as a numerical index, where
0corresponds to the first element in the listbox. (zero-indexed, obviously, she's a programmer) - active β indicates the element that has the location cursor. this element will be displayed with an underline when the listbox has the keyboard focus, and it is specified with the
activatemethod. - anchor β indicates the anchor point for the selection, which is set with the selection anchor method.
- end β indicates the end of the listbox. for most commands this refers to the last element in the listbox, but for a few commands such as
indexandinsertit refers to the element just after the last one. sneaky little shift, iykyk π - @x,y β indicates the element that covers the point in the listbox window specified by x and y (in pixel coordinates). if no element covers that point, then the closest element to that point is used. she'll find the nearest one, she's helpful like that π«Ά
in the method descriptions below, arguments named index, first, and last always contain text indices in one of the above forms.
π WIDGET METHODS π
the Listbox method creates a widget object. this object supports the configure and cget methods described in Tk::options which can be used to enquire and modify the options described above. the widget also inherits all the methods provided by the generic Tk::Widget class. so she's got moves you didn't even know about. iconic.
the following additional methods are available for listbox widgets:
$listbox->activate(index)β sets the active element to the one indicated by index. if index is outside the range of elements in the listbox then the closest element is activated. the active element is drawn with an underline when the widget has the input focus, and its index may be retrieved with the indexactive. β¨$listbox->bbox(index)β returns a list of four numbers describing the bounding box of the text in the element given by index. the first two elements of the list give the x and y coordinates of the upper-left corner of the screen area covered by the text (specified in pixels relative to the widget) and the last two elements give the width and height of the area, in pixels. if no part of the element given by index is visible on the screen, or if index refers to a non-existent element, then the result is an empty string; if the element is partially visible, the result gives the full area of the element, including any parts that are not visible. she tells you the whole truth even when the screen is gatekeeping π$listbox->curselectionβ returns a list containing the numerical indices of all of the elements in the listbox that are currently selected. if there are no elements selected in the listbox then an empty string is returned. (not me checking who's selected π)$listbox->delete(first, ?last?)β deletes one or more elements of the listbox. first and last are indices specifying the first and last elements in the range to delete. if last isn't specified it defaults to first, i.e. a single element is deleted. bye bestie π$listbox->get(first, ?last?)β if last is omitted, returns the contents of the listbox element indicated by first, or an empty string if first refers to a non-existent element. if last is specified, the command returns a list whose elements are all of the listbox elements between first and last, inclusive. both first and last may have any of the standard forms for indices. inclusive, because she's generous πΈ$listbox->index(index)β returns the integer index value that corresponds to index. if index isendthe return value is a count of the number of elements in the listbox (not the index of the last element). classic off-by-one trap, don't fall for it bestie π$listbox->insert(index, ?element, element, ...?)β inserts zero or more new elements in the list just before the element given by index. if index is specified asendthen the new elements are added to the end of the list. returns an empty string. β¨$listbox->itemcget(index, option)β returns the current value of the item configuration option given by option. option may have any of the values accepted by the listboxitemconfigurecommand.$listbox->itemconfigure(index, ?option, value, option, value, ...?)β query or modify the configuration options of an item in the listbox. if no option is specified, returns a list describing all of the available options for the item (seeTk_ConfigureInfofor information on the format of this list). if option is specified with no value, then the command returns a list describing the one named option (this list will be identical to the corresponding sublist of the value returned if no option is specified). if one or more option-value pairs are specified, then the command modifies the given widget option(s) to have the given value(s); in this case the command returns an empty string. the following options are currently supported for items:-background=> color β color specifies the background color to use when displaying the item. it may have any of the forms accepted byTk_GetColor. π¨-foreground=> color β color specifies the foreground color to use when displaying the item. it may have any of the forms accepted byTk_GetColor.-selectbackground=> color β color specifies the background color to use when displaying the item while it is selected. it may have any of the forms accepted byTk_GetColor. π-selectforeground=> color β color specifies the foreground color to use when displaying the item while it is selected. it may have any of the forms accepted byTk_GetColor.
$listbox->nearest(y)β given a y-coordinate within the listbox window, this command returns the index of the (visible) listbox element nearest to that y-coordinate. she's pointing at the one closest to you, so sweet π₯Ί$listbox->scan(option, args)β this command is used to implement scanning on listboxes. it has two forms, depending on option:$listbox->scanMark(x, y)β records x and y and the current view in the listbox window; used in conjunction with laterscan dragtocommands. typically this command is associated with a mouse button press in the widget. it returns an empty string. π±οΈ
$listbox->scanDragto(x, y.)β okay so this is the drag half of the scan duo π it takes yourxandyargs, does the math against thexandyfrom the last scan mark command on this widget, and shifts the view by 10 times that coordinate difference. It's usually wired to mouse motion events so it feels like you're yeeting the list through the window at high speed. What does it return? An empty string. That's it, that's the whole vibe. β¨$listbox->see(index)β makes the element atindexvisible, no cap. Already on screen? Then it does literally nothing, no effect. Chilling near an edge of the window? It scrolls just enough to bring that element flush to the edge. Anywhere else? It scrolls to center the element. It's giving "make sure everyone can see you, main character." π$listbox->selection(option, arg)β the big selection controller π and it has several forms depending on whatoptionyou hand it:$listbox->selectionAnchor(index)β sets the selection anchor to the element given byindex. Ifindexpoints at a non-existent element, the closest element gets used instead (no drama). The anchor is the end of the selection that stays fixed while you drag out a selection with the mouse. And yes, theanchorindex can be used to refer to that anchor element.$listbox->selectionClear(first, ?last?)β if any of the elements betweenfirstandlast(inclusive) are selected, they get deselected. Elements outside that range? Their selection state is not changed. Don't touch what you didn't come for. π$listbox->selectionIncludes(index)β returns1if the element atindexis currently selected,0if it isn't. Binary slay.$listbox->selectionSet(first, ?last?)β selects all the elements in the range betweenfirstandlast, inclusive, without affecting the selection state of anything outside that range. Boundaries respected, periodt.
$listbox->sizeβ returns a decimal string telling you the total number of elements in the listbox. It's the headcount bestie.$listbox->xview(args)β the horizontal scroll situation, query it or change it. Forms:$listbox->xviewβ returns a list of two elements, each a real fraction between0and1. Together they describe the horizontal span that's visible in the window. So like, if the first element is.2and the second is.6, then 20% of the listbox's text is off-screen to the left, the middle 40% is visible in the window, and 40% is off-screen to the right. These are literally the same values passed to scrollbars through the-xscrollcommandoption. π$listbox->xview(index)β adjusts the view so the character position given byindexis displayed at the left edge of the window. Character positions are defined by the width of the character0.$listbox->xviewMoveto( fraction );β adjusts the view sofractionof the total width of the listbox text is off-screen to the left.fractionmust be a fraction between0and1.$listbox->xviewScroll( number, what );β shifts the view left or right according tonumberandwhat.numbermust be an integer.whatmust be eitherunitsorpages(or an abbreviation of one of those). Ifwhatisunits, the view adjusts left or right bynumbercharacter units β that's the width of the0character. If it'spages, the view adjusts bynumberscreenfuls. Negativenumberβ characters farther to the left become visible; positive β characters farther to the right become visible. π
$listbox->yview(?args?)β the vertical counterpart, query it or change it. Forms:$listbox->yviewβ returns a list of two elements, both real fractions between0and1. First element = the position of the listbox element at the top of the window, relative to the whole listbox (0.5means it's halfway through the listbox, for example). Second element = the position of the listbox element just after the last one in the window, relative to the whole listbox. Same values that go to scrollbars via the-yscrollcommandoption. π¦$listbox->yview(index)β adjusts the view so the element given byindexis displayed at the top of the window.$listbox->yviewMoveto( fraction );β adjusts the view so the element given byfractionappears at the top of the window.fractionis a fraction between0and1;0indicates the first element in the listbox,0.33indicates the element one-third of the way through the listbox, and so on.$listbox->yviewScroll( number, what );β adjusts the view up or down according tonumberandwhat.numbermust be an integer.whatmust be eitherunitsorpages. Ifwhatisunits, the view adjusts up or down bynumberlines; if it'spages, it adjusts bynumberscreenfuls. Negativenumberβ earlier elements become visible; positive β later elements become visible. π
π DEFAULT BINDINGS π
Tk literally just gives you class bindings for listboxes that make them behave all Motif-ish, no cap. And the way a listbox acts is mostly decided by its selectMode option, which picks one of four whole vibes for handling the selection. π
If the selection mode is single or browse, then at most one element can be selected at once. In both of those modes, clicking button 1 on an element selects it and deselects whatever else was selected. And in browse mode you can also drag the selection around with button 1. π±οΈ
If the selection mode is multiple or extended, any number of elements can be selected at once β yes, even discontiguous ranges, we love a chaotic selection. π In multiple mode, clicking button 1 on an element toggles its selection state without touching any other elements. In extended mode, pressing button 1 on an element selects it, deselects everything else, and sets the anchor to the element under the mouse; then dragging the mouse with button 1 down extends the selection to include all the elements between the anchor and the element under the mouse, inclusive.
Real talk: most people are gonna want browse mode for single selections and extended mode for multiple selections. The other modes appear to be useful only in special situations. iykyk.
Any time the selection changes in the listbox, the virtual event <<ListboxSelect>> gets generated. It's easiest to bind to this event to be made aware of any changes to listbox selection. So do that. π«Ά
On top of all that, the default bindings also define this extra behavior:
- In
extendedmode, the selected range can be adjusted by pressing button 1 with the Shift key down: this modifies the selection to consist of the elements between the anchor and the element under the mouse, inclusive. The un-anchored end of this new selection can also be dragged with the button down. - In
extendedmode, pressing button 1 with the Control key down starts a toggle operation: the anchor is set to the element under the mouse, and its selection state is reversed. The selection state of other elements isn't changed. If the mouse is dragged with button 1 down, then the selection state of all elements between the anchor and the element under the mouse is set to match that of the anchor element; the selection state of all other elements remains what it was before the toggle operation began. - If the mouse leaves the listbox window with button 1 down, the window scrolls away from the mouse, making information visible that used to be off-screen on the side of the mouse. The scrolling continues until the mouse re-enters the window, the button is released, or the end of the listbox is reached.
- Mouse button 2 may be used for scanning. If it is pressed and dragged over the listbox, the contents of the listbox drag at high speed in the direction the mouse moves. ποΈ
- If the
UporDownkey is pressed, the location cursor (active element) moves up or down one element. If the selection mode isbrowseorextendedthen the new active element is also selected and all other elements are deselected. Inextendedmode the new active element becomes the selection anchor. - In
extendedmode,Shift-UpandShift-Downmove the location cursor (active element) up or down one element and also extend the selection to that element in a fashion similar to dragging with mouse button 1. - The
LeftandRightkeys scroll the listbox view left and right by the width of the character0.Control-LeftandControl-Rightscroll the listbox view left and right by the width of the window.Control-PriorandControl-Nextalso scroll left and right by the width of the window. - The
PriorandNextkeys scroll the listbox view up and down by one page (the height of the window). - The
HomeandEndkeys scroll the listbox horizontally to the left and right edges, respectively. Control-Homesets the location cursor to the the first element in the listbox, selects that element, and deselects everything else in the listbox.Control-Endsets the location cursor to the the last element in the listbox, selects that element, and deselects everything else in the listbox.- In
extendedmode,Control-Shift-Homeextends the selection to the first element in the listbox andControl-Shift-Endextends the selection to the last element. - In
multiplemode,Control-Shift-Homemoves the location cursor to the first element in the listbox andControl-Shift-Endmoves the location cursor to the last element. - The
spaceandSelectkeys make a selection at the location cursor (active element) just as if mouse button 1 had been pressed over this element. - In
extendedmode,Control-Shift-spaceandShift-Selectextend the selection to the active element just as if button 1 had been pressed with theShiftkey down. - In
extendedmode, theEscapekey cancels the most recent selection and restores all the elements in the selected range to their previous selection state. undo button but make it keyboard β¨ Control-slashselects everything in the widget, except insingleandbrowsemodes, in which case it selects the active element and deselects everything else.Control-backslashdeselects everything in the widget, except inbrowsemode where it has no effect.- The
F16key (labelledCopyon many Sun workstations) orMeta-wcopies the selection in the widget to the clipboard, if there is a selection.
And if you wanna switch any of this up? The behavior of listboxes can be changed by defining new bindings for individual widgets or by redefining the class bindings. Your listbox, your rules. π
π¦ TIED INTERFACE π¦
The Tk::Listbox widget can also be tied to a scalar or array variable, with different behaviour depending on the variable type, using these tie commands:
use Tk;
my ( @array, $scalar, $other );
my %options = ( ReturnType => "index" );
my $MW = MainWindow->new();
my $lbox = $MW->Listbox()->pack();
my @list = ( "a", "b", "c", "d", "e", "f" );
$lbox->insert('end', @list );
tie @array, "Tk::Listbox", $lbox
tie $scalar, "Tk::Listbox", $lbox;
tie $other, "Tk::Listbox", $lbox, %options;
currently only one modifier is implemented, a 3 way flag for tied scalars "ReturnType" which can have values "element", "index" or "both". The default is "element". π
πΈ Tied Arrays πΈ
If you tie an array to the Listbox you can manipulate the items currently contained by the box in the same manner as a normal array, e.g.
print @array;
push(@array, @list);
my $popped = pop(@array);
my $shifted = shift(@array);
unshift(@array, @list);
delete $array[$index];
print $string if exists $array[$i];
@array = ();
splice @array, $offset, $length, @list
The delete function is implemented slightly differently from the standard array implementation. Instead of setting the element at that index to undef it instead physically removes it from the Listbox. This has the effect of changing the array indices, so for instance if you had a list on non-continuous indices you wish to remove from the Listbox you should reverse sort the list and then apply the delete function, e.g.
my @list = ( 1, 2, 4, 12, 20 );
my @remove = reverse sort { $a <=> $b } @list;
delete @array[@remove];
would safely remove indices 20, 12, 4, 2 and 1 from the Listbox without problems. It should also be noted that a similar warning applies to the splice function (which would normally be used in this context to perform the same job). so like, be careful bestie π
π Tied Scalars π
Unlike tied arrays, if you tie a scalar to the Listbox you can retrieve the currently selected elements in the box as an array referenced by the scalar, for instance
my @list = ( "a", "b", "c", "d", "e", "f" );
$lbox->insert('end', sort @list );
$lbox->selectionSet(1);
inserts @list as elements in an already existing listbox and selects the element at index 1, which is "b". If we then
print @$selected;
this will return the currently selected elements, in this case "b".
However, if the "ReturnType" argument is passed when tying the Listbox to the scalar with value "index" then the indices of the selected elements will be returned instead of the elements themselves, ie in this case "1". This can be useful when manipulating both contents and selected elements in the Listbox at the same time. π
Importantly, if a value "both" is given the scalar will not be tied to an array, but instead to a hash, with keys being the indices and values being the elements at those indices.
You can also manipulate the selected items using the scalar. Equating the scalar to an array reference will select any elements that match elements in the Listbox, non-matching array items are ignored, e.g.
my @list = ( "a", "b", "c", "d", "e", "f" );
$lbox->insert('end', sort @list );
$lbox->selectionSet(1);
would insert the array @list into an already existing Listbox and select element at index 1, i.e. "b"
@array = ( "a", "b", "f" );
$selected = \@array;
would select elements "a", "b" and "f" in the Listbox.
Again, if the "index" we indicate we want to use indices in the options hash then the indices are use instead of elements, e.g.
@array = ( 0, 1, 5 );
$selected = \@array;
would have the same effect, selecting elements "a", "b" and "f" if the $selected variable was tied with %options = ( ReturnType => "index" ).
If we are returning "both", i.e. the tied scalar points to a hash, both key and value must match, e.g.
%hash = ( 0 => "a", 1 => "b", 5 => "f" );
$selected = \%hash;
would have the same effect as the previous examples.
Heads up: It should be noted that, despite being a reference to an array (or possibly a has), you still can not copy the tied variable without it being untied, instead you must pass a reference to the tied scalar between subroutines. π
β KEYWORDS β
listbox, widget, tied
π SEE ALSO π
Tk::HList, Tk::TextList.
okay that's the whole page, you're literally a Tk listbox expert now, no cap π This one's from perl v5.40.1, dated 2025-04-13, and it's Listbox(3pm). Go forth and select things bestie πβ¨π¦
π¦ where this page comes from
- debian trixie: perl-tk 1:804.036+dfsg1-5
- ubuntu questing: perl-tk 1:804.036+dfsg1-5
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms