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()

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

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()

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()

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)