8. tk Listbox
8.1. Usage
- listbox_widget = tk.Listbox(parent, option=value)
- parent is the window or frame object.Widget configuration options are supplied as keyword arguments, comma separated.e.g. listbox_widget = tk.Listbox(root, height=10, width=50)
8.2. Selection modes
The selectmode option determines how users can select items in a Listbox.
Selection mode |
Description |
|---|---|
|
Default mode. Only one item can be selected at a time. Dragging the mouse moves the selection to the item under the pointer. |
|
Only one item can be selected at a time. Clicking an item selects it and deselects any previously selected item. |
|
Multiple items can be selected independently. Click each item to toggle its selection without affecting other selected items. |
|
Allows multiple selections using standard keyboard and mouse combinations. Hold Shift to select a range of items or Ctrl (or Command on macOS) to select or deselect individual items. |
8.3. Indices
8.4. Using a listbox widget
This code creates a simple Tkinter GUI application that allows a user to select from a list.
import tkinter as tk # Import the tkinter module for GUI creation.
def get_selection(): # Define a function to get selected items from the listbox.
selected_indices = listbox.curselection() # Get indices of selected items.
selected_items = [listbox.get(i) for i in selected_indices] # Retrieve selected items.
output_label.config(text=f"Selected items:\n{', '.join(selected_items)}") # Display selected items in the label.
root = tk.Tk() # Create the main root.
root.geometry("400x400") # Set window size.
root.title("Listbox Example") # Set window title.
listbox = tk.Listbox(root, selectmode=tk.MULTIPLE, font=('calibre', 14, 'normal'), width=30, height=7) # Create a listbox widget.
listbox.pack(pady=10) # Add padding to the top of the listbox.
items = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"] # Define items to add to the listbox.
for item in items:
listbox.insert(tk.END, item) # Insert items into the listbox.
submit_button = tk.Button(root, text="Submit", font=('calibre', 14, 'normal'), command=get_selection) # Create a button to trigger the get_selection function.
submit_button.pack(pady=10) # Add padding to the button.
output_label = tk.Label(root, text="", font=('calibre', 14, 'normal'), width=50, height=3,
bd=2, highlightthickness=2, highlightbackground="gray") # Create a label to display the output.
output_label.pack(pady=10, padx=10) # Add padding around the label.
root.mainloop() # Run the main event loop.
8.5. Listbox methods
Tkinter's Listbox widget provides several methods for adding, removing, selecting, and retrieving items.
- curselection()
- Returns a tuple containing the indices of the selected items.e.g.
selected_indices = listbox.curselection()
- get(first, last=None)
- Returns the item at the specified index. If both
firstandlastare supplied, returns a tuple of items within the specified range.e.g.item = listbox.get(0)e.g.items = listbox.get(0, tk.END)
- insert(index, *elements)
- Inserts one or more items at the specified index.e.g.
listbox.insert(tk.END, "Apple")e.g.listbox.insert(0, "First Item")
- delete(first, last=None)
- Removes one item or a range of items from the listbox.e.g.
listbox.delete(0)e.g.listbox.delete(0, tk.END)
- selection_set(first, last=None)
- Selects one item or a range of items.e.g.
listbox.selection_set(0)e.g.listbox.selection_set(0, 2)
- selection_clear(first, last=None)
- Clears the selection from one item or a range of items.e.g.
listbox.selection_clear(0)e.g.listbox.selection_clear(0, 2)
- selection_includes(index)
- Returns
Trueif the specified item is currently selected.e.g.is_selected = listbox.selection_includes(3)
- size()
- Returns the total number of items in the listbox.e.g.
num_items = listbox.size()
- activate(index)
- Sets the active item to the specified index.e.g.
listbox.activate(4)
- see(index)
- Scrolls the listbox so the specified item is visible.e.g.
listbox.see(tk.END)
- nearest(y)
- Returns the index of the item nearest the specified y-coordinate.e.g.
index = listbox.nearest(event.y)
- bbox(index)
- Returns the bounding box
(x, y, width, height)of the specified item, orNoneif the item is not visible.e.g.box = listbox.bbox(0)
- index(index)
- Returns the numerical index corresponding to the specified index expression.e.g.
last = listbox.index(tk.END)
- itemconfig(index, option=value)
- Configures the display options for an individual item.e.g.
listbox.itemconfig(0, fg="red")e.g.listbox.itemconfig(2, bg="yellow")
8.6. Common tasks
Add an item
listbox.insert(tk.END, "New Item")
Insert an item at the beginning
listbox.insert(0, "First Item")
Remove the selected items
for index in reversed(listbox.curselection()):
listbox.delete(index)
Remove all items
listbox.delete(0, tk.END)
Select all items
listbox.selection_set(0, tk.END)
Clear the selection
listbox.selection_clear(0, tk.END)
Get the selected item (single selection)
index = listbox.curselection()[0]
item = listbox.get(index)
Get all selected items
selected_items = [listbox.get(i) for i in listbox.curselection()]
Scroll to the last item
listbox.see(tk.END)
Determine the number of items
count = listbox.size()
Check whether an item is selected
if listbox.selection_includes(3):
print("Item 3 is selected")
8.7. Option details
- listbox_widget = tk.Listbox(parent, option=value)
- parent is the window or frame object.Options can be passed as parameters separated by commas.
Parameters:
- activestyle
- Syntax:
listbox_widget = tk.Listbox(parent, activestyle="underline")Description: Sets the style of the active item.Default: underlineExample:listbox_widget = tk.Listbox(root, activestyle="underline")
- background
- bg
- Syntax:
listbox_widget = tk.Listbox(parent, bg="color")Description: Sets the background color of the listbox.Default: SystemWindowExample:listbox_widget = tk.Listbox(root, bg="SystemWindow")
- bd
- borderwidth
- Syntax:
listbox_widget = tk.Listbox(parent, bd=value)Description: Sets the border width of the listbox.Default: 1Example:listbox_widget = tk.Listbox(root, bd=1)
- cursor
- Syntax:
listbox_widget = tk.Listbox(parent, cursor="cursor_type")Description: Sets the cursor that appears when the mouse is over the listbox.Default: NoneExample:listbox_widget = tk.Listbox(root, cursor="arrow")
- disabledforeground
- Syntax:
listbox_widget = tk.Listbox(parent, disabledforeground="color")Description: Sets the foreground color of the listbox when it is disabled.Default: SystemDisabledTextExample:listbox_widget = tk.Listbox(root, disabledforeground="SystemDisabledText")
- exportselection
- Syntax:
listbox_widget = tk.Listbox(parent, exportselection=value)Description: Controls whether the selection is exported to the clipboard.Default: 1Example:listbox_widget = tk.Listbox(root, exportselection=1)On many platforms, exportselection=True causes the Listbox selection to be linked to the system's primary selection.Setting exportselection=False keeps the selection even when another widget gains focus.
- fg
- foreground
- Syntax:
listbox_widget = tk.Listbox(parent, fg="color")Description: Sets the foreground color of the listbox.Default: SystemButtonTextExample:listbox_widget = tk.Listbox(root, fg="SystemButtonText")
- font
- Syntax:
listbox_widget = tk.Listbox(parent, font="font")Description: Sets the font of the listbox text.Default: TkDefaultFontExample:listbox_widget = tk.Listbox(root, font="TkDefaultFont")
- height
- Syntax:
listbox_widget = tk.Listbox(parent, height=value)Description: Sets the height of the listbox in number of lines.Default: 10Example:listbox_widget = tk.Listbox(root, height=10)
- highlightbackground
- Syntax:
listbox_widget = tk.Listbox(parent, highlightbackground="color")Description: Sets the color of the focus highlight when the listbox does not have focus.Default: SystemButtonFaceExample:listbox_widget = tk.Listbox(root, highlightbackground="SystemButtonFace")
- highlightcolor
- Syntax:
listbox_widget = tk.Listbox(parent, highlightcolor="color")Description: Sets the color of the focus highlight when the listbox has focus.Default: SystemWindowFrameExample:listbox_widget = tk.Listbox(root, highlightcolor="SystemWindowFrame")
- highlightthickness
- Syntax:
listbox_widget = tk.Listbox(parent, highlightthickness=value)Description: Sets the thickness of the focus highlight.Default: 1Example:listbox_widget = tk.Listbox(root, highlightthickness=1)
- justify
- Syntax:
listbox_widget = tk.Listbox(parent, justify="left")Description: Sets the justification of the text within the listbox.Default: leftExample:listbox_widget = tk.Listbox(root, justify="left")
- relief
- Syntax:
listbox_widget = tk.Listbox(parent, relief="style")Description: Sets the 3D effect of the listbox border.Default: sunkenExample:listbox_widget = tk.Listbox(root, relief="sunken")
- selectbackground
- Syntax:
listbox_widget = tk.Listbox(parent, selectbackground="color")Description: Sets the background color of selected items.Default: SystemHighlightExample:listbox_widget = tk.Listbox(root, selectbackground="SystemHighlight")
- selectborderwidth
- Syntax:
listbox_widget = tk.Listbox(parent, selectborderwidth=value)Description: Sets the width of the border around selected items.Default: 0Example:listbox_widget = tk.Listbox(root, selectborderwidth=0)
- selectforeground
- Syntax:
listbox_widget = tk.Listbox(parent, selectforeground="color")Description: Sets the foreground color of selected items.Default: SystemHighlightTextExample:listbox_widget = tk.Listbox(root, selectforeground="SystemHighlightText")
- selectmode
- Syntax:
listbox_widget = tk.Listbox(parent, selectmode=tk.BROWSE)Description: Specifies how the user can select items in the listbox.Default:tk.BROWSEExample:listbox_widget = tk.Listbox(root, selectmode=tk.MULTIPLE)Selection modes:
Mode
Description
tk.BROWSEDefault. Allows a single item to be selected. Dragging the mouse moves the selection to the item under the pointer.
tk.SINGLEAllows only one item to be selected. Clicking an item selects it and deselects any previously selected item.
tk.MULTIPLEAllows multiple items to be selected independently by clicking each item. Clicking an already selected item deselects it.
tk.EXTENDEDAllows multiple selections using standard keyboard and mouse combinations. Hold Shift to select a range of items or Ctrl (or Command on macOS) to select or deselect individual items.
- setgrid
- Syntax:
listbox_widget = tk.Listbox(parent, setgrid=value)Description: Controls whether the listbox is gridded.Default: 0Example:listbox_widget = tk.Listbox(root, setgrid=0)
- state
- Syntax:
listbox_widget = tk.Listbox(parent, state="state")Description: Sets the state of the listbox (normal or disabled).Default: normalExample:listbox_widget = tk.Listbox(root, state="normal")
- takefocus
- Syntax:
listbox_widget = tk.Listbox(parent, takefocus=value)Description: Controls whether the listbox accepts focus.Default: NoneExample:listbox_widget = tk.Listbox(root, takefocus=1)
- width
- Syntax:
listbox_widget = tk.Listbox(parent, width=value)Description: Sets the width of the listbox in number of characters.Default: 20Example:listbox_widget = tk.Listbox(root, width=20)
- xscrollcommand
- Syntax:
listbox_widget = tk.Listbox(parent, xscrollcommand=callback)Description: Sets the horizontal scroll command.Default: NoneExample:listbox_widget = tk.Listbox(root, xscrollcommand=scrollbar.set)
- yscrollcommand
- Syntax:
listbox_widget = tk.Listbox(parent, yscrollcommand=callback)Description: Sets the vertical scroll command.Default: NoneExample:listbox_widget = tk.Listbox(root, yscrollcommand=scrollbar.set)
- listvariable
- Syntax:
listbox_widget = tk.Listbox(parent, listvariable=variable)Description: Sets the variable associated with the listbox.Default: NoneExample:listbox_widget = tk.Listbox(root, listvariable=my_var)e.g. items = tk.StringVar(value=("Red", "Green", "Blue"))e.g. listbox = tk.Listbox(root, listvariable=items)
8.8. Default options
Listbox option is shown below.import tkinter as tk
root = tk.Tk()
widget = tk.Listbox(root)
widget_options = widget.keys()
for option in widget_options:
print(f"{option}: {widget.cget(option)}") # cget retrieves the current value of the option