Listbox

Listbox#

tkinter.ListBox is an element that allows you to create a set of items so that you can select a subset of items for further manipulations.

import os
import tkinter as tk
from pathlib import Path
from random import randint

os.chdir(str(Path().resolve().parent.parent))

from tkinter_files.screenshot import take_screenshot

Insert#

The tkinter.ListBox.insert method allows you to add items to the list box.


The following cell creates a list box with 5 elements.

root = tk.Tk()

list_box = tk.Listbox()

list_box.pack()
for i in range(5):
    list_box.insert(tk.END, f'item {i}')

root.after(200, take_screenshot, root)
root.mainloop()
../../../_images/0485a969b1d8e5c7cf0325975391fb141dde960abf1890c8da1165f082b05616.png

Get#

With the tkinter.listbox.get method you can get the value under the specified element of the list.


The following cell creates a set of random listbox elements, and displays the contents of the third (index 2) in the print output.

root = tk.Tk()

list_box = tk.Listbox()
generate_line = lambda: "".join([chr(randint(ord("A"), ord("z"))) for i in range(5)])
list_box.pack()

for i in range(5):
    list_box.insert(tk.END, generate_line())

print("Element 2 is:", list_box.get(2))

root.after(200, take_screenshot, root)
root.mainloop()
Element 2 is: [XFtW
../../../_images/f34468186d755461fbade28804621d3af621ac78adbddcb8aa9dfb55f092371a.png

Delete#

With Listbox.delete(<index of the item>) you can delete any item from the list.


The following cell creates some elements and deletes an intermediate one - as a result, one element is missing.

root = tk.Tk()

list_box = tk.Listbox()

list_box.pack()
for i in range(5):
    list_box.insert(tk.END, f'item {i}')
list_box.delete(2)

root.after(200, take_screenshot, root)

root.mainloop()
../../../_images/5433aa3035a9289726bda9280202cb5a95a045fc5d7130ff646be38391c0765e.png

Selection#

There are the following tools that you can use to handle the selection in tk.Listbox:

  • selection_set: allows to specify indices that have to be selected.

  • curselection: allows to get indices of the currently selected items.

  • selectmode: is a field that allows to specify the behavior of the list box when something is selected.


The following cell creates the listbox and selects some items in it.

root = tk.Tk()
list_box = tk.Listbox()

list_box.pack()
for i in range(5):
    list_box.insert(tk.END, f'item {i}')

list_box.selection_set(2)
list_box.selection_set(4)

root.after(200, take_screenshot, root)
root.mainloop()
../../../_images/5c7429abbb16a985fd0f9fed2d9dd65dac0123d0a30b5a708669db746e404c81.png

As the result corresponding items seems to be selected.

The follwing cell shows the output of the curselection method.

list_box = tk.Listbox()

for i in range(5):
    list_box.insert(tk.END, f'item {i}')

list_box.selection_set(2)
list_box.selection_set(4)

list_box.curselection()
(2, 4)